Skip to content

Commit

Permalink
Added urlName function
Browse files Browse the repository at this point in the history
  • Loading branch information
adrenalin committed Apr 15, 2021
1 parent 5ea4290 commit f0430a1
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 1 deletion.
19 changes: 19 additions & 0 deletions lib/urlName.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Convert a string to URL safe
*
* @param { string } input Input string
* @return { string } URL safe version of the input
*/
module.exports = function urlName (input) {
if (typeof input !== 'string') {
throw new Error('urlName expects to receive a string')
}

return input
.toLowerCase()
.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
.replace(/[\s\n\r\t]+/g, '_')
.replace(/[^a-z0-9.-]+/g, '_')
.replace(/^_/, '')
.replace(/_$/, '')
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "helpers.js",
"version": "0.18.5",
"version": "0.19.0",
"description": "Miscellaneous helpers",
"main": "index.js",
"scripts": {
Expand Down
46 changes: 46 additions & 0 deletions tests/urlName.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const expect = require('expect.js')
const urlName = require('../lib/urlName')

describe('lib/urlName', () => {
it('should accept only a string', (done) => {
expect(urlName).withArgs('foo').not.to.throwError()
expect(urlName).withArgs(1).to.throwError()
expect(urlName).withArgs(new Date()).to.throwError()
expect(urlName).withArgs({ foo: 'bar' }).to.throwError()
done()
})

it('should not change lowercase ASCII-7 characters', (done) => {
const chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
expect(urlName(chars)).to.eql(chars)
done()
})

it('should convert uppercase ASCII-7 characters to lowercase', (done) => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
expect(urlName(chars)).to.eql('abcdefghijklmnopqrstuvwxyz0123456789')
done()
})

it('should convert diacritics to base forms', (done) => {
expect(urlName('èéêë')).to.eql('eeee')
expect(urlName('ÈÉÊË')).to.eql('eeee')
expect(urlName('ñ')).to.eql('n')
done()
})

it('should convert spaces to underscore', (done) => {
expect(urlName('A B')).to.eql('a_b')
done()
})

it('should replace all remaining characters excluding a-z, A-Z, 0-9, ., - and _', (done) => {
expect(urlName('A B&C!"D#0\'1.gif')).to.eql('a_b_c_d_0_1.gif')
done()
})

it('should remove leading and trailing underscores', (done) => {
expect(urlName('_abc_')).to.eql('abc')
done()
})
})

0 comments on commit f0430a1

Please sign in to comment.