Created
July 30, 2020 19:20
-
-
Save Matsukii/d2a665965d8f4bd9afaa56db9fea8d5e to your computer and use it in GitHub Desktop.
Construct an RegExp with items from prvided array, can be used to create an regex to test if have specific it. I used this some time ago and not remember if took some part from somewhere, so if i used something let me know
This file contains hidden or 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
| /** | |
| * @description construct an RegExp with items from prvided array, | |
| * can be used to create an regex to test if have specific item | |
| * | |
| * @param {Array<*>} items array of items to add as regex option | |
| * @param {String} flags regex flags | |
| * @returns {RegExp} RegExp | |
| * @example construct(["foo", "bar"], "gi").test("foo") -> true | |
| */ | |
| function construct(items, flags = 'gi'){ | |
| let reg = `(\\/?)(`; | |
| items.forEach((item, i) => { | |
| reg = reg.concat(`^${item}$`); | |
| if(i+1 < items.length){ | |
| reg = reg.concat('|'); | |
| } | |
| }); | |
| reg = reg.concat(`)(\\/?)`); | |
| return new RegExp(reg, flags) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment