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

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

#1

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);

#2

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


#3

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.


#4

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);