String to regex

I get a regex string from the server. for instance

js_pattern = "/^9\d+$/"

And I need to get the same regular expression from this line (without any changes)

js_regexp = /^9\d+$/

re = new RegExp(js_pattern) not working for me because in this case I get /\/^9d+$\//

Are there any correct options for converting a string to a regular expression in JavaScript?

+4
source share
3 answers

try:

re = new RegExp(js_pattern.slice(1,-1))

UPDATE:

in order to satisfy the limit without any changes , here is the path, perhaps not the best:

eval(js_pattern)

but since '\' is an escape character in JavaScript, you must replace '\' with '\\' on the server side.

UDDATE:

If you get the line "/ ^ 9 \ d + $ /", you have nothing to do on the server side.

+1

.

// true, because it non-special so it gets evaluated to that character.
console.log("\a" === "a"); // true

// false, because it the new line special character.
console.log("\n" === "n"); // false

JavaScript

:

, .

+1

It really depends on your server-side code, but essentially your problem is what \dis evaluated in the string as an escaped character. My solution is specific to PHP, but other server languages ​​should have similar ones.

// drop the enclosing slashes, either here or in JS land
$jsPattern = addslashes("^9\d+$");
// $jsPattern => "^9\\d+$"

Now on the JS side you can use this:

var js_exp = new RegExp(js_pattern);

The easiest option is to simply remove the enclosed slashes and add an additional slash slash yourself if you can.

0
source

All Articles