One test failing, but explicit check returns true

Tell us what’s happening:
I have used .split(/\s/g), but I don’t know why the 3rd test is failing. I even tried to explicitly compare with the answer, and it returns true. Please tell me what is the mistake here.

  **Your code so far**

// Only change code below this line
function urlSlug(title) {
  let arr=title.toLowerCase().trim().split(/\s/g);
  return arr.join('-');
}
// Only change code above this line
console.log(urlSlug(" Winter Is Coming")==="winter-is-coming");  //prints true
  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:88.0) Gecko/20100101 Firefox/88.0.

Challenge: Apply Functional Programming to Convert Strings to URL Slugs

Link to the challenge:

Hello!
There’s a small issue in your code as it replaces any whitespace character with a dash. The third test has two whitespaces between the words “Is Coming” but should only return one dash (not two).
There is regexp available which will only catch whitespace once, even if it is repeated for several characters.

Does that make sense? :slight_smile:

2 Likes

Thank you very much… :grinning: :grinning:
I understood the mistake I was making. I thought that in /<regex>/g, the g tag captures multiple occurrences too… Now, I had to revisit the chapter to understand it does not do so.

Exactly :slight_smile:
the g tag makes sure to catch all matches - not just the first match. BUT if your regex only searches for numbers and you have the number “21”, it will match first 2 then 1. Instead, you could use the regex /[0-9]+/g which will catch any numbers including all following numbers. So a string saying “I am 21 years old” would match “21” together but not separately.

I hope you understand it better now and are able to implement the + in your RegExp for the challenge to solve it :slight_smile:

2 Likes

Thank you for the clarification. I now understand the g tag, and its difference compared to using + inside regex. That was very helpful :heart:

1 Like

No worries!
Glad to be helpful :slight_smile:
Feel free to hop back onto the forums if you are uncertain or unable to solve a challenge again! :smiley:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.