Update slugify.md

This commit is contained in:
Angelos Chalaris
2020-10-04 10:36:38 +03:00
committed by GitHub
parent 0c705c1936
commit 68dd9e2966

View File

@ -1,25 +1,21 @@
--- ---
title: slugify title: slugify
tags: function,intermediate tags: string,regexp,intermediate
--- ---
Convert a string to a URL-friendly slug. Converts a string to a URL-friendly slug.
- Make the string lowercase and remove leading or trailing whitespace. - Use `String.prototype.toLowerCase()` and `String.prototype.trim()` to normalize the string.
- Remove all characters that are not words, whitespace or hyphens. - Use `String.prototype.replace()` to replace spaces, dashes and underscores with `-` and remove special characters.
- Replace whitespace with a single hyphen (`-`).
- Remove any leading or trailing hyphens.
```js ```js
const slugify = (string) => { const slugify = str =>
const slug = string str
.toLowerCase() .toLowerCase()
.trim() .trim()
.replace(/[^\w\s-]/g, '') .replace(/[^\w\s-]/g, '')
.replace(/[\s_-]+/g, '-') .replace(/[\s_-]+/g, '-')
.replace(/^-+|-+$/g, ''); .replace(/^-+|-+$/g, '');
return slug;
};
``` ```
```js ```js