Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active October 7, 2015 12:28
Show Gist options
  • Save nathansmith/3165179 to your computer and use it in GitHub Desktop.
Save nathansmith/3165179 to your computer and use it in GitHub Desktop.
Escape characters that could break regex.
function regex(x) {
// Escape the string.
function esc(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
// Used in loop.
var arr, i;
// Is it an array?
if (Object.prototype.toString.call(x) === '[object Array]') {
arr = [];
i = x.length;
while (i--) {
arr.push(esc(x[i]));
}
return new RegExp(arr.join('|'), 'g');
}
// Assume individual string.
else {
return new RegExp(esc(x), 'g');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment