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
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"
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,'@')
© 2023 OneMinuteCode. All rights reserved.