Skip to content

Commit

Permalink
fix: honor special character replacements in charmap
Browse files Browse the repository at this point in the history
This now returns the expected result with `_` included:

```
slug.charmap._ = '_'
slug('foo_bar baz') // 'foo_bar-baz' but was previously 'foobar-baz'
```

Fixes: Trott#198
  • Loading branch information
Trott committed Apr 16, 2021
1 parent 0437a31 commit f5e18c9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
12 changes: 8 additions & 4 deletions slug.js
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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, '')
}
Expand Down
5 changes: 5 additions & 0 deletions test/slug.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down

0 comments on commit f5e18c9

Please sign in to comment.