Skip to content

Instantly share code, notes, and snippets.

@Matsukii
Created July 30, 2020 19:20
Show Gist options
  • Select an option

  • Save Matsukii/d2a665965d8f4bd9afaa56db9fea8d5e to your computer and use it in GitHub Desktop.

Select an option

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
/**
* @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