From a8806546e38ca10ffd3db559dff1abc2dc67e5ad Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 10 May 2021 22:12:33 -0700 Subject: [PATCH] fix: remove replacement char from start and end in strict mode In addition to fixing the bug, this also removes dynamically generated regular expresions which could result in unexpected behavior when the replacement character is a special character in regulard expressions, such as `.`. Refs: https://github.com/simov/slugify/issues/112#issuecomment-836365587 --- slugify.js | 25 +++++++++++-------------- test/slugify.js | 4 ++++ 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/slugify.js b/slugify.js index 56f4b8f..277111b 100644 --- a/slugify.js +++ b/slugify.js @@ -34,23 +34,20 @@ return result + (locale[ch] || charMap[ch] || (ch === replacement ? ' ' : ch)) // remove not allowed characters .replace(options.remove || /[^\w\s$*_+~.()'"!\-:@]+/g, '') - }, '') - // trim leading/trailing spaces - .trim() - // convert spaces to replacement character - // also remove duplicates of the replacement character - .replace(/\s+/g, replacement) + }, ''); - if (options.lower) { - slug = slug.toLowerCase() + if (options.strict) { + slug = slug.replace(/[^A-Za-z0-9\s]/g, ''); } - if (options.strict) { - // remove anything besides letters, numbers, and the replacement char - slug = slug - .replace(new RegExp('[^a-zA-Z0-9' + replacement + ']', 'g'), '') - // remove duplicates of the replacement character - .replace(new RegExp('[\\s' + replacement + ']+', 'g'), replacement) + // Remove leading/trailing spaces, then replace all other spaces with + // replacement character, treating multiple consecutive spaces as a single + // space. + slug = slug.trim() + .replace(/\s+/g, replacement); + + if (options.lower) { + slug = slug.toLowerCase() } return slug diff --git a/test/slugify.js b/test/slugify.js index 1b6a98c..32a8db0 100644 --- a/test/slugify.js +++ b/test/slugify.js @@ -257,4 +257,8 @@ describe('slugify', () => { it('replaces leading and trailing replacement chars', () => { t.equal(slugify('-Come on, fhqwhgads-'), 'Come-on-fhqwhgads') }) + + it('replaces leading and trailing replacement chars in strict mode', () => { + t.equal(slugify('! Come on, fhqwhgads !', { strict: true }), 'Come-on-fhqwhgads') + }) })