Created
June 15, 2017 08:59
-
-
Save vojtatranta/4ce9f1c46af7fea83ae92589876a0386 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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