How to create RegExp from its string representation in JavaScript?

I have a string containing a regular expression in literal notation, for example:

var pattern = '/abc/i';

How to create a regex object from this line?

Of course, I could just use eval:

eval(pattern); // /abc/i

But I would like to avoid this.

+4
source share
3 answers

Perhaps you can do something like this:

var pattern = '/ab*c/gi';

if ((m = /^\/(.*)\/([gim]*)$/i.exec(pattern)) != null) {
   restr = m[1], flag = m[2], re = new RegExp(restr, flag)
}
//=> /ab*c/gi

You may need to add processing for special regular expression metacharacters if you want them to be processed literally.

+2
source

I just created a function for this. Check it out.

  • 1 ( /) /). → pattenr.
  • / +1 →

2 new RegExp

function formRegEx(str){
  var reg=str.substring(1,str.lastIndexOf('/'));
  var flags=str.substring(str.lastIndexOf('/')+1,str.length);
  return new RegExp(reg,flags);
  
}
console.log(formRegEx('/abc/i'));
console.log(formRegEx('/[a-zA-Z]/ig'));
Hide result

Update

OP , abc/i , .

, ,

/^\/.*\/[igm]*$/

//

/[^\\]\/[^igm]/

function formRegEx(str){
  if(!/^\/.*\/[igm]*$/.test(str)) return "Invalid RE";
  if(/[^\\]\/[^igm]/.test(str)) return "Invalid RE";
  var reg=str.substring(1,str.lastIndexOf('/'));
  var flags=str.substring(str.lastIndexOf('/')+1,str.length);
  return new RegExp(reg,flags);
  
}
console.log(formRegEx('/abc/ig')); // true
console.log(formRegEx('/abc//i'));  // false
console.log(formRegEx('/a/bc/i')); //false
console.log(formRegEx('/[a-zA-Z]/ig')); // true
console.log(formRegEx('abc/ig'));  // invalid
console.log(formRegEx('abci')); // invalid
console.log(formRegEx('/abc/ik')); // invalid
Hide result
+2

You can use the combo substrand lastIndexOfas follows:

var pattern = '/abc/i';

// the index of the first "/" is always 1
var index = pattern.lastIndexOf('/');          // index of the last "/"

var thePattern = pattern.substr(1, index - 1); // the actual pattern part
var theFlags   = pattern.substr(index + 1);    // the flags part

var regex = new RegExp(thePattern, theFlags);

console.log(regex);
Run codeHide result
+2
source

Source: https://habr.com/ru/post/1673976/


All Articles