diff --git a/snippets/slugify.md b/snippets/slugify.md new file mode 100644 index 000000000..4bd803463 --- /dev/null +++ b/snippets/slugify.md @@ -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' +``` diff --git a/snippets/yesterday.md b/snippets/yesterday.md index b343d4cb7..8fd6d3088 100644 --- a/snippets/yesterday.md +++ b/snippets/yesterday.md @@ -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]; };