Is there a way to use RegExp to replace a substring surrounded by '/*' on the left, and '*/' on the right. The substring can include anything (numbers, underscore, special characters)
var string = "abc /*abcd_^&^djh:*/ <-abcd_.";
function replace(string, regexp, replacement="") {
return string.replaceAll(new RegExp(regexp), replacement);
}
let regexpReplacement; //The RegExp for a substring surounded by "/*" and "*/"
console.log(replace(string, regexpReplacement));
//Should output "abc <-abcd_."
CodePudding user response:
Perfect time to use a lazy 0-unlimited quantifier.
Regex101 explanation: https://regex101.com/r/JHxYKh/1
Basically:
Match /*, then anything as lazily as possible (with *?) so that the next */ won't be absorbed, then */. The global flag allows replaceAll to work.
var string = "abc /*abcd_^&^djh:*/ <-abcd_.";
function replace(string, regexp, replacement="") {
return string.replaceAll(new RegExp(regexp), replacement);
}
let regexpReplacement = /\/\*.*?\*\//g;
console.log(replace(string, regexpReplacement));
//Should output "abc <-abcd_."
If you want multiline support, use this: https://regex101.com/r/mrPmYQ/1
