Files
30-seconds-of-code/snippets/js/s/string-to-slug.md
Angelos Chalaris 9d032ce05e Rename js snippets
2023-05-19 20:23:47 +03:00

28 lines
617 B
Markdown

---
title: String to slug
type: snippet
language: javascript
tags: [string,regexp]
cover: collab-desk-2
dateModified: 2020-10-04T10:36:38+03:00
---
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'
```