Some Pixels en / pt

Escape any String to be "Regular-Expression-safe"

In Ruby, there is a method called Regexp.escape that escapes any String to be used inside a Regular Expression. This is useful when you want to get the user input and use it inside a RegExp, without breaking it.

In JavaScript, there is no such method, but I found this nice little snippet to create one:

RegExp.escape = function(s) {
    return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
};

Now using:

new RegExp( RegExp.escape("jQuery-[1.8]") , "gi" )

Will result /jQuery\-\[1\.8\]/gi ;)

This snippet is very useful and you can probably port it to any other language.