freeCodeCamp Challenge Guide: Apply Functional Programming to Convert Strings to URL Slugs

Apply Functional Programming to Convert Strings to URL Slugs


Solutions

Solution 1 (Click to Show/Hide)
// the global variable
var globalTitle = "Winter Is Coming";

// Add your code below this line
function urlSlug(title) {
  return title
    .split(/\W/)
    .filter(obj => {
      return obj !== "";
    })
    .join("-")
    .toLowerCase();
}
// Add your code above this line

var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"
Solution 2 (Click to Show/Hide)
// the global variable
var globalTitle = "Winter Is Coming";

// Add your code below this line
function urlSlug(title) {
  return title
    .toLowerCase()
    .trim()
    .split(/\s+/)
    .join("-");
}
// Add your code above this line

var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"
24 Likes

I am having trouble understanding the second solution at .split(/\s+/). Can someone explain the what happens to the white space?

4 Likes

@rickyalatorre One or more white space characters is the delimiter, so the white space characters are removed and the array only has the words (non-white space characters).

19 Likes