Is there a way to use variables in the regular expression literal?

Asked 1 years ago, Updated 1 years ago, 59 views

Using RegExp, generate regular expression objects from the variable str in the following format

let regexp = new RegExp(str+'(.*?), 'gmi');

Is it possible to write in the regular expression literal?

I could only think of the following code, which was not a regular expression object

let regexp='/'+str+'(.*?)'+'/gmi';

I would appreciate it if you could give me your advice.

javascript regular-expression

2022-09-30 11:15

2 Answers

Please refer to the article below.

Javascript Regex: How to put a variable inside a regular expression?

Attempting to embed a string in the regular expression literal in Chrome 71.0 failed.That means you can't.

>a
"abc"
>/${a}/
/${a}/
>`${a}`
"abc"


2022-09-30 11:15

If you force yourself to do it on the event, it will look like this.

function var_replace(s,reg,tgt){
var repstr='\'+s+'\'.replace('+reg+',\"+tgt+'\')'
return value(repstr)
}

var str = 'abcdef1234+-=';
Due to the string specification of varreg='/\\d/g'//javascript, the backslash must be double
console.log(str.replace(/\d/g, '@')
console.log(str.replace(reg, '@')
console.log(var_replace(str,reg,'@')


2022-09-30 11:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.