Created
January 25, 2017 20:05
-
-
Save cpsubrian/60526a4da313856d665c3c2ff7a563b5 to your computer and use it in GitHub Desktop.
Create a regex from parts using a tagged template.
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
function regexSupplant (strings, ...values) { | |
let parts = [] | |
while (strings.length || values.length) { | |
if (strings.length) { | |
parts.push(strings.shift() | |
.split('\n') | |
.map((val) => val.trim()) | |
.join('') | |
) | |
} | |
if (values.length) { | |
parts.push(values.shift() | |
.toString() | |
.replace(/(^\/)|(\/$)/g, '') | |
) | |
} | |
} | |
const regexpish = parts.join('') | |
const pattern = regexpish.replace(/^\/|\/\w*$/g, '') | |
const flags = (/\/(\w*)$/g).exec(regexpish)[1] | |
return new RegExp(pattern, flags) | |
} | |
const validMentionPrecedingChars = /(?:^|[^a-zA-Z0-9_!#$%&*@@]|(?:^|[^a-zA-Z0-9_+~.-])(?:rt|RT|rT|Rt):?)/; | |
const atSigns = /[@@]/; | |
const screenName = /[a-zA-Z0-9_]{1,20}/; | |
const list = /\/[a-zA-Z][a-zA-Z0-9_\-]{0,24}/; | |
const validMentionOrList = regexSupplant`/ | |
(${validMentionPrecedingChars}) | |
(${atSigns}) | |
(${screenName}) | |
(${list})? | |
/g`; | |
console.log(validMentionOrList); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment