mirror of https://github.com/abpframework/abp.git
3 changed files with 41 additions and 1 deletions
@ -0,0 +1,22 @@ |
|||||
|
import { createTokenParser } from '../utils/string-utils'; |
||||
|
|
||||
|
describe('String Utils', () => { |
||||
|
describe('#createTokenParser', () => { |
||||
|
const parseTokens = createTokenParser('{subDomain}.{domain}.{gtld}|{domain}.{gtld}'); |
||||
|
|
||||
|
test.each` |
||||
|
url | subDomain | domain | gtld |
||||
|
${'www.example.com'} | ${'www'} | ${'example'} | ${'com'} |
||||
|
${'test.sub.example.com'} | ${'test.sub'} | ${'example'} | ${'com'} |
||||
|
${'example.com'} | ${undefined} | ${'example'} | ${'com'} |
||||
|
`(
|
||||
|
'should return subDomain as $subDomain, domain as $domain, and gtld as $gtld when url is $url', |
||||
|
({ url, subDomain, domain, gtld }) => { |
||||
|
const parsed = parseTokens(url); |
||||
|
expect(parsed.subDomain[0]).toBe(subDomain); |
||||
|
expect(parsed.domain[0]).toBe(domain); |
||||
|
expect(parsed.gtld[0]).toBe(gtld); |
||||
|
}, |
||||
|
); |
||||
|
}); |
||||
|
}); |
||||
@ -0,0 +1,17 @@ |
|||||
|
export function createTokenParser(format: string) { |
||||
|
return (string: string) => { |
||||
|
const tokens: string[] = []; |
||||
|
const regex = format.replace(/\./g, '\\.').replace(/\{\s?([0-9a-zA-Z]+)\s?\}/g, (_, token) => { |
||||
|
tokens.push(token); |
||||
|
return '(.+)'; |
||||
|
}); |
||||
|
|
||||
|
const matches = (string.match(regex) || []).slice(1); |
||||
|
|
||||
|
return matches.reduce((acc, v, i) => { |
||||
|
const key = tokens[i]; |
||||
|
acc[key] = [...(acc[key] || []), v].filter(Boolean); |
||||
|
return acc; |
||||
|
}, {} as Record<string, string[]>); |
||||
|
}; |
||||
|
} |
||||
Loading…
Reference in new issue