Skip to content
Open
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
12 changes: 10 additions & 2 deletions slug.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ function symbols(code) {
return _symbols[code];
}

function escapeChar(ch) {
if (!ch) { return ""; }
var out = ch.charCodeAt(0).toString(16);
while (out.length < 4) { out = "0" + out; }
return "\\u" + out;
}

function slug(string, opts) {
string = string.toString();
if ('string' === typeof opts)
Expand Down Expand Up @@ -61,9 +68,10 @@ function slug(string, opts) {
if (opts.remove) char = char.replace(opts.remove, ''); // add flavour
result += char;
}
var replacement_re = escapeChar(opts.replacement);
result = result.replace(/^\s+|\s+$/g, ''); // trim leading/trailing spaces
result = result.replace(/[-\s]+/g, opts.replacement); // convert spaces
result = result.replace(opts.replacement+"$",''); // remove trailing separator
result = result.replace(new RegExp("[\\s"+replacement_re+"]+", "g"), opts.replacement); // convert spaces
result = result.replace(new RegExp("^"+replacement_re+"|"+replacement_re+"$", "g"),''); // remove leading/trailing separators
if (opts.lower)
result = result.toLowerCase();
return result;
Expand Down
10 changes: 10 additions & 0 deletions test/slug.test.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ describe 'slug', ->
[slug 'foo bar baz', '_'].should.eql ['foo_bar_baz']
[slug 'foo bar baz', ''].should.eql ['foobarbaz']

it 'should remove duplicate custom separators', ->
text = "looooooooooooool"
expected = "lol"
[slug text, 'o'].should.eql [expected]

it 'should remove trailing space if any', ->
[slug ' foo bar baz '].should.eql ['foo-bar-baz']

Expand Down Expand Up @@ -228,6 +233,11 @@ describe 'slug', ->
expected = "its-your-journey-we-guide-you-through."
[slug text, mode:'rfc3986'].should.eql [expected]

it 'should trim leading / trailing separators', ->
text = "--words go here--"
expected = "words-go-here"
[slug text, mode:'rfc3986'].should.eql [expected]

it 'should allow disabling of lowercase', ->
text = "It's Your Journey We Guide You Through."
expected = "Its-Your-Journey-We-Guide-You-Through."
Expand Down