RegExp. quoteText()

# Axel Rauschmayer (12 years ago)

This must have been suggested before, but it would be great to have a built-in function for quoting text in a RegExp.

For example:

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

If you wanted to be extra thorough, you could include parens, braces and brackets.

# Claude Pache (12 years ago)

The complete list of characters that should be escaped is:

	. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

(taken from 1). Importantly, characters that have special meaning only in some context should also be included. For example, consider the hyphen -, which has special meaning only inside [...]: People may want to write:

	var charList = 'abcd123-_';
	var re = new RegExp( '[' + RegExp.quote(charList) + ']' )

in order to construct a regexp that matches any character of charList.

# Andrea Giammarchi (12 years ago)

quick one: the hyphen has meaning only inside squared brackets and between ranges ... this has no meaning [_-] so doesn't this [a-]