I have a RegExp problem that I need help with.
I have two strings str1 = "abcde $a1$ cdeg $x$ fghj $v8$ ABCDEa1FGH $a1$ LMN"and str2 = "NMNa1CD (a1+x)/(v8-x+a1) dgd". I replaced T1 for a1, T2 for x, T3 for v8 in str1 (those between $...$). Now I want to replace according to that rule (T1 for a1,...) in str2, but only the elements in the mathematical expression, I did the following:
I take out all the elements between $..$ in str1 (a1, x, v8) to form an array:
I extracted all the elements between $..$ in the string str1 to form an array:
var $str$ = str1.match(/\$+[^$]+\$/g).toString();
var str = $str$.substring(1,$str$.length-1);
var wr = str.match(/\w\d|[a-z]/g);
var newWr = unique(wr);//here is a function that merges duplicate elements in an array
I then find and replace the elements in the string str2:
for (var i =0;i <= newWr.length-1;i++){
var x = newWr[i];
var str2 = str2.replace(x,"T"+(i+1));
Logger.log(str2);
Of course when running the above code, all a1, x, v8 elements will be replaced. While I just want to replace the elements that are in the math expression (a1+x)/(v8-x+a1). I used RegExp as follows
var str2 = str2.replace(/x(?=\W)/g,"T"+(i+1));
But it didn't work. I have researched a lot about RegExp but I have not found a solution. I ask for your help, thanks.
Your solution is almost correct, but the x in the regex should be the value of variable x not letter x. So the following should fix that issue.
for (let i = 0; i <= newWr.length - 1; i++) {
let x = newWr[i];
const regex = new RegExp(`${x}(?=\\W)`, 'g');
str2 = str2.replace(regex, "T" + (i + 1));
}
console.log(str2); // NMNa1CD (T1+T2)/(T3-T2+T1) dgd