Converting Strings to URL Slugs

Tell us what’s happening:
Hello. Currently my code meets all the requirements except for:

urlSlug(" Winter Is Coming") should return "winter-is-coming"

I cannot understand why it doesn’t work for double spaces. Could you advise me how to fix it please?

Your code so far


// the global variable
var globalTitle = "Winter Is Coming";

// Add your code below this line
function urlSlug(title) {
  
 return title.split(" ").join("-").toLowerCase(); 
}
// Add your code above this line

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

Your browser information:

Chrome Version 75.0.3770.100 (Official Build) (64-bit)

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/apply-functional-programming-to-convert-strings-to-url-slugs

Your code returns -winter-is-coming

Yeah, but how to make it only write - between words?

when you split the string, you end with an array with one element being an empty string. You can remove it there.

Or there are methods to remove spaces at the beginning or at the end of a string

Can you think of an Array method that can “filter” out the empty elements? Remember that an empty string is a falsy value.

Boolean("")
false
1 Like

Thank you, I used

function urlSlug(title) {

return title.split(" “).filter(Boolean).join(”-").toLowerCase();
}

that’s a way, and it works also if your string has multiple spaces between words