Trouble with Converting Strings to URL Slugs

Hey guys, I’m doing the convert strings to URL slugs challenge within the Javascript courses Functional Programming module, and I’ve come across an issue in my code.

// the global variable

var globalTitle = "Winter Is Coming";

// Add your code below this line

function urlSlug(title) {

let splitArr = Array.from(title.split(/\W+/));

console.log(splitArr);

let lowerArr = splitArr.map((elem) => elem.toLowerCase());

console.log(lowerArr);

let fin = lowerArr.reduce((combined, word) => combined + "-" + word);

console.log(fin);

return fin;

}

// Add your code above this line

console.log(urlSlug("Winter is  coming"));

var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"

Basically, all tests pass except the one with two spaces in between two words. How do I get “Winter is coming” to return properly with only one dash between “is” and “coming”? I’ve tried adding a + after the \W regex but it doesn’t seem to work. BTW arrow functions aren’t displaying properly here: “=>” should be “=>”.

1 Like

Can you trim the white space in front of the first word?

https://www.w3schools.com/jsref/jsref_trim_string.asp

So I think you are over engineering this problem a little. Using regex method match will return an array and the part you missed in the regex was after a word you want to stop the match if there is white space.

title = title.toLowercase();
title = title.match(/\w+\S/g);
return title.join('-');