lab.joelgillman.com

Sketches, Code Bites and Toys




Escape User Input for JavaScript Regex
2011-07-12

Escaping strings for regular expressions in JavaScript is pretty easy when you know what you’re doing. But say that the input is dynamic, possibly coming from an inexperienced user. That shit has got to be scrubbed! Unfortunately, there is no built in way to do that. Luckily it’s easy enough to add it in yourself.

Just pop this code in and you’re good to go!

RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
RegExp.escape("($2 + $4) × 2 = $12");
// Outputs
// "\(\$2\ \+\ \$4\)\ ×\ 2\ =\ \$12"

Thanks to Simon Willison who blogged about it first!



Share
Tags: , , ,

trackback URL for this post: http://lab.joelgillman.com/archives/186_escape-user-input-for-javascript-regex/trackback

comments as feed

Post a Comment

Your email is never published nor shared.
Required fields are marked *
*
*

 



© 2012 jgillman -¦- Go WordPress! -¦- RSS 2.0 Feed