Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: remove replacement char from start and end in strict mode #116

Merged
merged 1 commit into from
May 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 11 additions & 14 deletions slugify.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions test/slugify.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
})
})