Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
74
rated 0 times [  78] [ 4]  / answers: 1 / hits: 183879  / 14 Years ago, tue, august 24, 2010, 12:00:00

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 have got to be something standard out there.


More From » regex

 Answers
26

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.


[#95822] Sunday, August 22, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mireyag

Total Points: 73
Total Questions: 107
Total Answers: 85

Location: Ukraine
Member since Sun, Dec 13, 2020
3 Years ago
mireyag questions
Sun, Aug 15, 21, 00:00, 3 Years ago
Wed, Dec 16, 20, 00:00, 3 Years ago
Tue, Sep 1, 20, 00:00, 4 Years ago
Sun, Jul 5, 20, 00:00, 4 Years ago
;