Functional Programming: Apply Functional Programming to Convert Strings to URL Slugs

Correct solution and passes every test in console but keep telling its not.

// the global variable
var globalTitle = "Winter Is   Coming";

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

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

console.log(winterComing);

Nope, not really…
" Hello world" will return “-hello-world”. It should be “hello-world”. I think you can figure out why.

1 Like

You can use the trim() method to remove the spaces at the both ends.

I used the match() method instead of trim and split so it just matches the given words and you don’t need to deal with spaces.

If you split the string using /[\s.,’-]/gi regex expression , then returned array would be ["", “winter”, “is”, “coming”], since empty strings = to false, you can use filter method, to filter them out.

—working solution—

var globalTitle = "Winter Is Coming";

function urlSlug(title) {
  return title.toLowerCase().split(/[\s.,'-]/gi).filter((x) => x).join("-");
  
}
var winterComing = urlSlug(globalTitle);