In Perl, there's a function named quotemeta
which accepts a string and returns a regex pattern that matches that string. It's used in virtually every program to avoid code injection bugs.
One would use quotemeta
when dynamically building a pattern. For example,
"^"+quotemeta(var)+"_\\d+$"
A JavaScript implementation follows:
function quotemeta(s) {
return String(s).replace(/\W/g, "\\$&");
}
Given how needed this function when working with regex patterns, I would have expected JavaScript to provide one. Does JavaScript or jQuery already have such a function?