Alright now with everything we've learned so far, let's apply it to another problem.
Many sites have the titles of a post added to part of the URL. For example, if you write a Medium post titled anime bookbags, it's likely the URL would have some form of the title string in it (.../anime-bookbags).
Let's complete this function so it converts a string title and returns the hyphenated version for the URL.
Here are some Hints:
The input is a string with spaces and title-cased words
The output is a string with the spaces between words replaced by a hyphen (-)
The output should be all lower-cased letters
The output should not have any spaces
function url(title) {
}
Answer:
function url(title) {
return title
.toLowerCase()
.split(" ")
.filter(str => str != "") // <-- basically saying if the str being passed is not equal to an empty string return that str
.join("-")
}
console.log(url(" Good Anakin Good"))
ur.lSlug(" Good Anakin Good") returns the string "Good-Anakin-Good"
An improved (although still naive) function might be:
consturlSlug=str=>str.trim().toLowerCase().replace(/[^a-z0-9 ]+/g,'')// remove anything non-alphanumeric (keeping spaces).replace(/ +/g,'-')// replace any spaces or groups of spaces with a hyphen
It's naive as it won't cope well with accented letters, Cyrillic characters, other alphabets & writing systems, emojis, etc.
Writing a decent all-purpose slug generator isn't actually that easy
Top comments (4)
You can shorten your filter function to:
since any non-empty string is truthy and empty string is falsey.
Also, if the slug is to be used in URLs - you may want to look at removing characters that are not URL safe
An improved (although still naive) function might be:
It's naive as it won't cope well with accented letters, Cyrillic characters, other alphabets & writing systems, emojis, etc.
Writing a decent all-purpose slug generator isn't actually that easy
Nice
function urlSlug(title) {
let arr = title.split(/\W/);
return arr.filter(s => s != "").join("-").toLowerCase();
}