-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
6 changed files
with
529 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
# js-slug | ||
|
||
This package as no dependency and let you transform any string with special chars into a nice string with only Alpha, Digits and dash caracters. | ||
Typical use : Transform a title into a url segment. | ||
|
||
# Usage | ||
If you use npm, you'll need node >12 because it's a ESM. | ||
- `npm install @tpoisseau/slug` | ||
|
||
```js | ||
import slug from '@tpoisseau/slug'; | ||
``` | ||
|
||
If you wan't use it directly in browser | ||
|
||
```js | ||
import slug from 'https://github.com/tpoisseau/js-slug/blob/master/index.mjs'; | ||
``` | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export default function slug(str: string): string; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
/** | ||
* Slugify a string | ||
* | ||
* 1. normalize NFKD : https://en.wikipedia.org/wiki/Unicode_equivalence#Normalization | ||
* 2. non-ascii chars will be removed | ||
* 3. non-alphanum chars transformed into a dash | ||
* 4. trim dash | ||
* | ||
* @param {string} str - the string to slugify (is casted to String for avoir errors) | ||
* | ||
* @returns {string} slugified string | ||
*/ | ||
export default function slug(str='') { | ||
// transform to string if not | ||
return String(str) | ||
.normalize('NFKD') // https://en.wikipedia.org/wiki/Unicode_equivalence#Normalization | ||
.toLowerCase() | ||
.replace(/[^\x00-\x7F]+/g, '') // remove non-ascii chars | ||
.replace(/[^a-z0-9]+/g, '-') // replace non-alphanum chars into a dash | ||
.replace(/^-+/, '') // trimStart dashes | ||
.replace(/-+$/, '') // trimEnd dashes | ||
; | ||
} |
Oops, something went wrong.