Almost had it with this

So I wrote:

function urlSlug(title) {
return title.split(" ").map(char => char.toLowerCase()).join("-");

it works for every case except if the string title starts with a space. How to account for that?

You also have trouble with console.log(urlSlug("Winter Is Coming")) due to the same root issue.

Try this:

  "Winter Is  Coming"
    .split(" ")

What do you see where the double space in between “Is” and “Coming” occurs?


There is an empty string ‘between’ those two spaces. Can you get rid of those empty strings?

I think something like this but still doesn’t delete opening white space at start of string. Adding ^ didn’t help.

console.log(title.split(/\s+/).map(char => char.toLowerCase()).join("-"));

Think simpler. You want to filter out those empty strings.

When you split on a character, there will be an array item created before each one found. So if your string starts with that character, it will create an empty entry at the start of the array and if you have two of that character in a row, there will be an empty entry there as well.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.