Drill

ProblemsJavaScript › text

Turn a product title into a URL slug

mediumtextJavaScript

The catalogue builds a URL from each product title, and the result has to be safe to put in a path.

slugify(title: string) → string

Solve it in the editor →

Where you start

function slugify(title) {
  
}

Worked examples

CallResult
slugify(" Blue Widget, 12mm! ")"blue-widget-12mm"
slugify("A---B")"a-b"
slugify("Already-slugged")"already-slugged"
slugify("!!!")""

Hint

Append a dash only when there is already something to separate, then trim the one you may have left on the end.

Reference solution in JavaScript
function slugify(title) {
  let result = '';
  for (const ch of title.toLowerCase()) {
    if ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) result += ch;
    else if (result.length > 0 && !result.endsWith('-')) result += '-';
  }
  return result.endsWith('-') ? result.slice(0, -1) : result;
}

The same problem in another language

More text problems in JavaScript