I am working on a functional programming exercise and I was asked to replace all whitespaces in the string with an hyphen. If I have a string like This is a title, the output should be this-is-a-title.
Now, all cases as described before work but I have an edge case string like this: Peter Is Coming. I would like to strip out the whitespace that is before the Coming so that my final output is peter-is-coming which would be the equivalent output for when I have an initial string of Peter is Coming with no redundant whitespace. I was able to do that of before Peter with ease using the trim method. How do I go about this edge case's?
Note: One of the constraints is that there shouldn't be the use of the replace method.
Thanks.
My code:
function urlSlug(title) {
const url = title.trim().toLowerCase();
console.log(url);
const splitURL = url.split("");
// console.log(splitURL);
const urlArr = [];
const filtered = splitURL.filter(val => {
if (/\s/.test(val)) {
urlArr.push("-");
}
else {
urlArr.push(val);
}
});
return console.log(urlArr.join(""));
}
urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone"); // a-mind-needs-books-like-a-sword-needs-a-whetstone
urlSlug("Hold The Door"); // hold-the-door
urlSlug(" Peter is Coming"); // peter-is--coming
// The last output is what I get but not what I want to achieve.
Update:
Thanks to everybody that answered. I eventually used the code below in relation to my original code and it passed the edge case:
function urlSlug(title) {
const url = title.trim().toLowerCase();
console.log(url);
const splitURL = url.split(/\s+/);
// console.log(splitURL);
const urlArr = [];
const filtered = splitURL.filter(val => {
if (/\s/.test(val)) {
urlArr.push("-");
}
else {
urlArr.push(val);
}
});
return console.log(urlArr.join("-"));
}
The condition
if (/\s/.test(val))doesn't consider consecutive whitespace characters between words.You can try the following way: