feat: add slugify and use const in yesterday

This commit is contained in:
Vincent
2020-10-04 08:45:43 +02:00
parent 7081232e8e
commit 423084cc8b
2 changed files with 28 additions and 1 deletions

27
snippets/slugify.md Normal file
View File

@ -0,0 +1,27 @@
---
title: slugify
tags: function,intermediate
---
Convert a string to a URL-friendly slug.
- Make the string lowercase and remove leading or trailing whitespace.
- Remove all characters that are not words, whitespace or hyphens.
- Replace whitespace with a single hyphen (`-`).
- Remove any leading or trailing hyphens.
```js
const slugify = (string) => {
const slug = string
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '')
.replace(/[\s_-]+/g, '-')
.replace(/^-+|-+$/g, '');
return slug;
};
```
```js
slugify('Hello World!'); // 'hello-world'
```

View File

@ -10,7 +10,7 @@ Results in a string representation of yesterday's date.
```js
const yesterday = () => {
let t = new Date();
const t = new Date();
t.setDate(t.getDate() - 1);
return t.toISOString().split('T')[0];
};