DEV Community

Randy Rivera
Randy Rivera

Posted on Edited on

Apply Functional Programming to Convert Strings to URL Slugs

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:

  1. The input is a string with spaces and title-cased words
  2. The output is a string with the spaces between words replaced by a hyphen (-)
  3. The output should be all lower-cased letters
  4. The output should not have any spaces
function url(title) {


}
Enter fullscreen mode Exit fullscreen mode
  • 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"))
Enter fullscreen mode Exit fullscreen mode
  • ur.lSlug(" Good Anakin Good") returns the string "Good-Anakin-Good"

Top comments (4)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

You can shorten your filter function to:

s => s
Enter fullscreen mode Exit fullscreen mode

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

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

An improved (although still naive) function might be:

const urlSlug = 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
Enter fullscreen mode Exit fullscreen mode

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

Collapse
 
biomathcode profile image
Pratik sharma

Nice

Collapse
 
francesito profile image
Francesito

function urlSlug(title) {
let arr = title.split(/\W/);
return arr.filter(s => s != "").join("-").toLowerCase();
}