Home > OS >  How do I use a regular expression from a string variable
How do I use a regular expression from a string variable

Time:10-21

In my current project, I have a CMS that is supplying all the data. One field of that CMS is for regular expressions, which allows me to enter my own specific expressions to check in the front end. My problem is that when I pull the regular expression it is coming through the escaped characters, and I can not seem to find a way to get around this.

The expression that I am using is /^\d $/. As I mentioned this is stored inside my CMS and I am attempting to use it in the following code:

            const re = /^\d $/;
            const rea = new RegExp(this.question.QuestionExpression);
            console.log(re);
            console.log(rea);
            console.log(this.answer)
            console.log(re.test(this.answer));
            console.log(rea.test(this.answer));
            console.log(this.answer.toString().match(this.question.QuestionExpression))

this.question.QuestionExpression is the Regular expression that is coming in from the CMS. The problem is not getting it, but how to interperet once I have it. const re is currently just being used as a test and has no real bearing on the final outcome.

The outcome from the above code is as follows:

/^\d $/
/\/^\d $\//
13 
true 
false 
null

As you can see in the second line, it is adding escape characters which are causing it to fail on the 5th line. I am sure that I am missing something simple, but any advice would be greatly appreciated.

CodePudding user response:

You don't include the / at the start and end when you are using a RegExp from a string.

const pattern = new RegExp('^a.*z');
console.log(pattern.test('abcdefghijklmnopqrstuvwxyz'));
console.log(pattern.test('zydhfkjadhsfkjlahsdkla'));

So, if your string is including those slashes, or may include those slashes, simply strip them off:

const strWithSlashes = '/abc/';
const str = strWithSlashes.replace(/(^\/|\/$)/g, '');
console.log(str);

const pattern = new RegExp(str);
console.log(pattern.test('cake abc cookies'));
console.log(pattern.test('cake cookies'));

CodePudding user response:

If your regex from the CMS looks like /^\d $/ it is likely the string representation of the regex. In contrast, new RegExp() expects a string representing the regex pattern without the leading and trailing /, so you need to strip them:

const fromCMS = '/^\\d $/'; // escaped `\` so that string becomes `/^\d $/`
const re1 = /^\d $/;
const re2 = new RegExp(fromCMS.replace(/^\//, '').replace(/\/$/, ''));
console.log(re1);
console.log(re2);
[ '12', '2x' ].forEach(str => {
  console.log(str   ' => re1: '   re1.test(str)   ', re2: '   re2.test(str));
});
Output:

/^\d $/
/^\d $/
12 => re1: true, re2: true
2x => re1: false, re2: false

In case the regex string from the CMS contains modifiers you can extract that, and supply as a second parameter to the new RegExp()

  • Related