Skip to content

Instantly share code, notes, and snippets.

@vojtatranta
Created June 15, 2017 08:59
Show Gist options
  • Save vojtatranta/4ce9f1c46af7fea83ae92589876a0386 to your computer and use it in GitHub Desktop.
Save vojtatranta/4ce9f1c46af7fea83ae92589876a0386 to your computer and use it in GitHub Desktop.
/* eslint quotes: ["double", "single"] */
import chai, { expect } from 'chai'
const createRegex = (str) => {
return `^${
str
.replace(/\/+/g, '/')
.replace(/:.+?(\/|$)/g, (pattern, g1) => {
return `(\\d+)${g1}`
})
}?$`
}
describe('regex', () => {
it('should construct a regex', () => {
const url = '/ahoj/123/'
const match = '/ahoj/:id/'
const resultRegex = "^/ahoj/(\\d+)/?$"
const stringRex = createRegex(match)
console.log(stringRex)
expect(stringRex).to.equal(resultRegex)
const regex = new RegExp(stringRex, 'g')
console.log('reg', regex)
expect(regex.test('/ahoj/3/')).to.be.ok
expect(regex.test('/ahoj/3')).to.be.ok
})
it('should construct multiple regex', () => {
const url = '/ahoj/123/123'
const match = '/ahoj/:id/:id/'
const resultRegex = "^/ahoj/(\\d+)/(\\d+)/?$"
const stringRex = createRegex(match)
console.log(stringRex)
expect(stringRex).to.equal(resultRegex)
const regex = new RegExp(stringRex, 'g')
expect(regex.test('/ahoj/3/4/')).to.be.ok
expect(regex.test('/ahoj/3/4')).to.be.ok
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment