Convert regex string to regex object that contains unicode character class escape

54 Views Asked by At

I have a data object with regex in it

data = {regex : "/^[\p{L} .’_-]+$/u"}

In js file I am using this pattern to match with a string

var s = "check";
var pattern = new RegExp(data.regex);
console.log(pattern.test(s));

The above code is not working. Pattern becomes //^[p{L} .’_-]+$/u/ and is resulting to false and extra slashes are also getting attached to the regex.

How to fix this so the result can be something like this pattern = /^[\p{L} .’_-]+$/u but in regex object?

Also, there is a difference when console.log of values takes place.

const [, regexx, flags] = regex.match(/^\/(.*)\/([a-z]*)$/);
const pattern = new RegExp(regexx, flags);
console.log(pattern); //  /^[\p{L} .’_-]+$/u


var sampleregex = /^[\p{L} .’_-]+$/u
console.log(sampleregex) //  /^(?:[ \x2D\.A-Z_a-z\xAA\xB5\x....

Why is so and how to make pattern variable behave the same way?

1

There are 1 best solutions below

4
Hao Wu On

Assuming the backslash in your regex string \p{L} has been escaped. You might need a regex to match the regex, and extract the regex string and flags such as:

^\/(.*)\/([a-z]*)$

Here's a running example:

const data = { regex : "/^[\\p{L} .’_-]+$/u" };

// extract the regex string and flags(optional)
const [, regex, flags] = data.regex.match(/^\/(.*)\/([a-z]*)$/);

const s = "check";
const pattern = new RegExp(regex, flags);

console.log(pattern);
console.log(pattern.test(s));