diff --git a/README.md b/README.md index 385d7b0..15644e9 100644 --- a/README.md +++ b/README.md @@ -26,11 +26,23 @@ slugify('some string', { remove: undefined, // remove characters that match regex, defaults to `undefined` lower: false, // convert to lower case, defaults to `false` strict: false, // strip special characters except replacement, defaults to `false` + strictReplace: false, // replace special characters except replacement with replacement character, defaults to `false` locale: 'vi', // language code of the locale to use trim: true // trim leading and trailing replacement chars, defaults to `true` }) ``` +## Strict replace + +Set `strictReplace` to `true` to replace special characters with the configured +replacement character instead of removing them. Consecutive replacements are +collapsed and leading or trailing ones are removed when `trim` is `true`. +When both `strict` and `strictReplace` are `true`, `strict` takes precedence. + +```js +slugify('foo_bar. -@-baz!', {strictReplace: true}) // foo-bar-baz +``` + ## Remove For example, to remove `*+~.()'"!:@` from the result slug, you can use `slugify('..', {remove: /[*+~.()'"!:@]/g})`. diff --git a/slugify.d.ts b/slugify.d.ts index 78a9d7f..23662b8 100644 --- a/slugify.d.ts +++ b/slugify.d.ts @@ -16,6 +16,7 @@ declare function slugify( remove?: RegExp; lower?: boolean; strict?: boolean; + strictReplace?: boolean; locale?: string; trim?: boolean; } diff --git a/slugify.js b/slugify.js index dd13ebf..feb5a38 100644 --- a/slugify.js +++ b/slugify.js @@ -46,6 +46,10 @@ slug = slug.replace(/[^A-Za-z0-9\s]/g, ''); } + if (options.strictReplace) { + slug = slug.replace(/[^A-Za-z0-9\s]/g, ' '); + } + if (trim) { slug = slug.trim() } diff --git a/test/slugify.js b/test/slugify.js index 356c4b7..4ec4abd 100644 --- a/test/slugify.js +++ b/test/slugify.js @@ -72,6 +72,27 @@ describe('slugify', () => { t.equal(slugify('foo_bar. -@-baz!', {strict: true}), 'foobar-baz') }) + it('options.strictReplace', () => { + t.equal(slugify( + 'foo_bar. -@-baz!', + {strictReplace: true} + ), 'foo-bar-baz') + }) + + it('options.strictReplace uses the configured replacement and trims it', () => { + t.equal(slugify( + '_foo@bar_', + {strictReplace: true, replacement: '_'} + ), 'foo_bar') + }) + + it('options.strict takes precedence over options.strictReplace', () => { + t.equal(slugify( + 'foo@bar', + {strict: true, strictReplace: true} + ), 'foobar') + }) + it('options.strict - remove duplicates of the replacement character', () => { t.equal(slugify('foo @ bar', {strict: true}), 'foo-bar') })