skip to Main Content

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?

2

Answers


  1. To include Unicode character class escapes, the "u" flag should be added outside of the pattern.

    Here’s the remediated code:

    let data = {regex : "^[p{L} .’_-]+$"}
    
    // You should separate your regex string from flags.
    let split = data.regex.split('/');
    let pattern = new RegExp(split[1], 'u'); // Specifying unicode flag "u" separately.
    
    let s = "check";
    console.log(pattern.test(s));
    
    Login or Signup to reply.
  2. Correctly escaping the backslashes in the regex pattern and using a Unicode range ([u0000-uFFFF]) instead of Unicode property escapes (p{}). This ensures that the pattern is properly interpreted and matches the desired characters in the input string. the below code returns true.

    var data = { regex: "^[\u0000-\uFFFF .’_-]+$" }; // Unicode range for
    all characters
    
    var s = "check";
    var pattern = new RegExp(data.regex);
    console.log(pattern.test(s)); // Output: true
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search