From f5e18c9ff8e21e5c5bc636f34b811b4b73e1b204 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Thu, 15 Apr 2021 21:41:29 -0700 Subject: [PATCH] fix: honor special character replacements in charmap This now returns the expected result with `_` included: ``` slug.charmap._ = '_' slug('foo_bar baz') // 'foo_bar-baz' but was previously 'foobar-baz' ``` Fixes: https://github.com/Trott/slug/issues/198 --- slug.js | 12 ++++++++---- test/slug.test.js | 5 +++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/slug.js b/slug.js index 7af5944..baef398 100644 --- a/slug.js +++ b/slug.js @@ -171,6 +171,8 @@ // sort lengths in descending order. lengths = lengths.sort(function (a, b) { return b - a }) + const disallowedChars = opts.mode === 'rfc3986' ? /[^\w\s\-.~]/ : /[^A-Za-z0-9\s]/ + let result = '' for (let char, i = 0, l = string.length; i < l; i++) { char = string[i] @@ -190,14 +192,16 @@ char = localeMap[char] } else if (opts.charmap[char]) { char = opts.charmap[char] + } else if (char.includes(opts.replacement)) { + // preserve the replacement character in case it is excluded by disallowedChars + char = char.replace(opts.replacement, ' ') + } else { + char = char.replace(disallowedChars, '') } } - // next line preserves the replacement character in case it is included in allowedChars - char = char.replace(opts.replacement, ' ') result += char } - const allowedChars = opts.mode === 'rfc3986' ? /[^\w\s\-.~]/g : /[^A-Za-z0-9\s]/g - result = result.replace(allowedChars, '') // allowed + if (opts.remove) { result = result.replace(opts.remove, '') } diff --git a/test/slug.test.js b/test/slug.test.js index 1e2ba46..6a185ae 100644 --- a/test/slug.test.js +++ b/test/slug.test.js @@ -82,6 +82,11 @@ describe('slug', function () { }) }) + it('should preserve punctuation added to charmap', function () { + slug.charmap._ = '_' + assert.strictEqual(slug('foo_bar baz'), 'foo_bar-baz') + }) + it('should replace latin chars', function () { const charMap = { À: 'A',