Last active
December 15, 2015 09:59
-
-
Save nathansmith/5242077 to your computer and use it in GitHub Desktop.
Helper function for building regular expressions from arrays.
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
/* | |
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