Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active December 15, 2015 09:59
Show Gist options
  • Save nathansmith/5242077 to your computer and use it in GitHub Desktop.
Save nathansmith/5242077 to your computer and use it in GitHub Desktop.
Helper function for building regular expressions from arrays.
/*
Used like this:
var regex = regex_escape([
'foo',
'bar',
'http://example.com/page'
]);
OR:
var regex = regex_escape('http://example.com/page');
It will escape any characters that could
break a regular expression, so you don't
have to type out all that junk manually.
*/
// Escape regular expression
function regex_escape(thing) {
// Escape the string
function esc(str) {
return str.toString().replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}
// Used in loop
var arr, i;
// Is it an array?
if (Object.prototype.toString.call(thing) === '[object Array]') {
arr = [];
i = thing.length;
while (i--) {
arr.push(esc(thing[i]));
}
return new RegExp(arr.join('|'), 'g');
}
// Assume individual string
else {
return new RegExp(esc(thing), 'g');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment