Spot the bug - #157: Slug Formatter

One regex bug in this formatter.

function slugify(title) {
  return title.trim().toLowerCase().replace('/\s+/g', '-');
}

console.log(slugify('Hello World Again'));

Reply with what is broken and how you would fix it.

Yo the regex is a string literal right now. you gotta remove the quotes around /\s+/g.

Spot the Bug answer: The regular expression is passed as a string literal instead of a RegExp object.

The fix:

replace(/\s+/g, '-')

Why:
When a string is passed as the first argument to replace(), it is treated as a literal string to be matched, not a regular expression. This means the function attempts to replace the exact string ā€˜/\s+/g’ which is not present in the input, leaving spaces unchanged.

First-answer leaderboard

  1. @emmawalter5 - 8 (firsts) :trophy:
  2. @kirupa - 8 (firsts) :trophy:
  3. @Apexcodes - 6 (firsts)
  4. @adnanahmed - 2 (firsts)