Merge pull request #1264 from vincentdoerig/patch-1

Add slugify
This commit is contained in:
Angelos Chalaris
2020-10-04 10:36:56 +03:00
committed by GitHub

23
snippets/slugify.md Normal file
View File

@ -0,0 +1,23 @@
---
title: slugify
tags: string,regexp,intermediate
---
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.
```js
const slugify = str =>
str
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '')
.replace(/[\s_-]+/g, '-')
.replace(/^-+|-+$/g, '');
```
```js
slugify('Hello World!'); // 'hello-world'
```