The function linked in another answer is insufficient. It fails to escape ^
or $
(start and end of string), or -
, which in a character group is used for ranges.
Use this function:
function escapeRegex(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
While it may seem unnecessary at first glance, escaping -
(as well as ^
) makes the function suitable for escaping characters to be inserted into a character class as well as the body of the regex.
Escaping /
makes the function suitable for escaping characters to be used in a JavaScript regex literal for later evaluation.
As there is no downside to escaping either of them, it makes sense to escape to cover wider use cases.
And yes, it is a disappointing failing that this is not part of standard JavaScript.