Convert string to kebab case

Published on August 25th, 2019

javascript icon

This conversion may seem strange at the first glance but it is very useful. For example, you use this to calculate slugs for from blog post title. It eliminates a chance to make typo writing your slugs. Happened to me many times.

string
  .replace(/([a-z])([A-Z])/g, '$1-$2') // get all lowercase letters that are near to uppercase ones
  .replace(/[\s_]+/g, '-') // replace all spaces and low dash
  .toLowerCase() // convert to lower case