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.
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.
Your regex is a string literal, not a RegExp, so . replace() is looking for the exact characters "/\s+/g" instead of matching whitespace. Fix it by using a real regex (no quotes): title. trim(). toLowerCase(). replace(/\s+/g, '-').
Spot the Bug answer: The regex is passed as a string ā/\s+/gā instead of an actual regex literal, so replace() only replaces the first literal occurrence of that exact string (which never matches).
The fix:
return title.trim().toLowerCase().replace(/\s+/g, '-');
Why:
String.prototype.replace treats a quoted ā/\s+/gā as a plain string to search for, not as a regular expression, so whitespace is never matched or replaced globally. Using an actual regex literal /\s+/g enables global whitespace matching and correct replacement.
:: Copyright KIRUPA 2024 //--