Skip to content

Instantly share code, notes, and snippets.

@StuPig
Created September 20, 2012 03:54
Show Gist options
  • Save StuPig/3753884 to your computer and use it in GitHub Desktop.
Save StuPig/3753884 to your computer and use it in GitHub Desktop.
string escaped ( copied from YUI library )
/**
Returns a copy of the specified string with special regular expression
characters escaped, allowing the string to be used safely inside a regex.
The following characters, and all whitespace characters, are escaped:
- $ ^ * ( ) + [ ] { } | \ , . ?
If _string_ is not already a string, it will be coerced to a string.
@method regex
@param {String} string String to escape.
@return {String} Escaped string.
@static
**/
function regex(string) {
// There's no need to escape !, =, and : since they only have meaning
// when they follow a parenthesized ?, as in (?:...), and we already
// escape parens and question marks.
return (string + '').replace(/[\-$\^*()+\[\]{}|\\,.?\s]/g, '\\$&');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment