Update slugify.md
This commit is contained in:
@ -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
|
||||||
|
|||||||
Reference in New Issue
Block a user