Saturday, April 21, 2018

regex - Is there a RegExp.escape function in Javascript?




I just want to create a regular expression out of any possible string.



var usersString = "Hello?!*`~World()[]";
var expression = new RegExp(RegExp.escape(usersString))
var matches = "Hello".match(expression);


Is there a built in method for that? If not, what do people use? Ruby has RegExp.escape. I don't feel like I'd need to write my own, there's gotta be something standard out there. Thanks!


Answer




The function linked above 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:



RegExp.escape= function(s) {
return s.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 JS regex literal for later eval.



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...