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?
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:
console.log(
"Winter Is Coming"
.split(" ")
);
What do you see where the double space in between âIsâ and âComingâ occurs?
Answer:
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.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.