Functional Programming to Convert Strings to URL Slugs EXERCISE DOUBT

Functional Programming to Convert Strings to URL Slugs EXERCISE DOUBT
0

#1

Hi!

I was doing my code but I kept failing, so I checked for solutions on the forum, and for my surprise, my code was VERY similar to the answers, but with one difference, and I don’t understand why is my code not correct.

This is my code:

var globalTitle = "Winter Is Coming";

function urlSlug(title) {
  
  var newSlug = title.toLowerCase()
  .split(/\s+/)
  .filter(function(x){return x != " ";})
  .join("-");
  return newSlug;

}

var winterComing = urlSlug(globalTitle); 

And this is the solution:

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

// Add your code below this line
function urlSlug(title) {
  
  var newSlug = title.toLowerCase()
  .split(/\s+/)
  .filter(function(x){return x != "";})
  .join("-");
  return newSlug;
  
}
// Add your code above this line

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

The difference is the “” and the " ", that has a white space inside. The correct one is the empty one. Why is that?

I appreciate any help!

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/apply-functional-programming-to-convert-strings-to-url-slugs

edit. I tried to highlight the part I was strying to specify, but I don’t know how…anyways, it’s the filter part.


#2

Whenever confused, I always use my friend console.log and just start consoling out the results along the way to see what is happening.

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

// Add your code below this line
function urlSlug(title) {
  
  var newSlug = title.toLowerCase()
  .split(/\s+/)
  
  console.log('after split', newSlug)
  
  newSlug = newSlug.filter(function(x){return x != "";})
  
  console.log('after filter', newSlug)
  
  newSlug = newSlug.join("-");
  
  console.log('after join', newSlug)
  return newSlug;
  
}
// Add your code above this line

var winterComing = urlSlug(globalTitle); 

Here is a pen.

Plug in the different test cases and see what happens.


#3

It fails for the string " Winter Is Coming". Try that and see what the output is.


#4

I did not think that it would work that well with codepen! I tried with what you said but it works fine, I mean, I don’t see why you say it is not working.


#5

The difference is the line above. Your filter callback function returns the check of “is x not equal to a space character?” and the passing solution’s filter callback function returns the check of “is x not equal to a blank string?”.


#6

When I run my pen, I get this:

after split Array(4) 0: "" 1: "winter" 2: "is" 3: "coming"length: 4__proto__: Array(0)
after filter Array(3) 0: "winter" 1: "is" 2: "coming"length: 3__proto__: Array(0)
after join winter-is-coming

This shows why you need to filter out an empty string.