30秒学会 JavaScript 片段 · 2023年10月15日

30秒学会 JavaScript 片段 – String to slug

Converts a string to a URL-friendly slug.

  • Use String.prototype.toLowerCase() and String.prototype.trim() to normalize the string.
  • Use String.prototype.replace() to replace spaces, dashes and underscores with - and remove special characters.

代码实现

const slugify = str =>
  str
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '')
    .replace(/[\s_-]+/g, '-')
    .replace(/^-+|-+$/g, '');

slugify('Hello World!'); // 'hello-world'

翻译自:https://www.30secondsofcode.org/js/s/string-to-slug