This is one of the solutions provided by FCC. Although I used another solution to pass the challenge, I have troubles understanding the following code.
Why is it return obj !== ""; ? What does it mean by ""?
function urlSlug(title) {
return title
.split(/\W/)
.filter(obj => {
return obj !== "";
})
.join("-")
.toLowerCase();
}
You’re using a built in JavaScript method for arrays: filter. That method needs a callback function that returns either true or false. Here’s the callback function:
obj => {
return obj !== "";
}
Maybe it makes a bit more sense now, if you think about what that function returns.
Thank you for your help guys! I got it now.
I thought .split(/\W/) will not return an element for the extra non-character. But it actually return an empty str.
you can use \W+ so that it actually splits on one or more, but you still have eventual characters at the beginning or the end to remove (also remember that when you use \W the underscore will not be removed)