Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
tpoisseau committed Sep 25, 2019
1 parent 0621864 commit eb6bc0a
Show file tree
Hide file tree
Showing 6 changed files with 529 additions and 0 deletions.
19 changes: 19 additions & 0 deletions README.md
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';
```

1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default function slug(str: string): string;
23 changes: 23 additions & 0 deletions index.mjs
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
;
}
Loading

0 comments on commit eb6bc0a

Please sign in to comment.