0

I'm trying to replace an entire variable within an expression. The variable is preceded by either a start-of-string character (carat) or a pipe, and proceeded by either an end-of-string character (dollar sign) or a pipe. I need to replace the entire variable, including preceding and proceeding characters, with a pipe. I have the following code to capture the variable:

fullVar1 = new RegExp("((\||^)" + "(" + var1 + ")" + "(\||$))");

and the following code to replace the variable:

expression = expression.replace(fullVar1.exec(expression)[1], "\|");

Sadly, any pipes that should have been captured as part of the variable are left behind, although non-pipe characters are replaced as they should be.

Example input:

expression = "A|~A|B";
var1 = A;
var1 = ~A;

Processing: fullVar1 = new RegExp("((\||^)" + "(" + var1 + ")" + "(\||$))"); fullVar1 = new RegExp("((\||^)" + "(" + var1 + ")" + "(\||$))");

expression = expression.replace(fullVar1.exec(expression)[1], "\|");
expression = expression.replace(fullVar2.exec(expression)[1], "\|");

Expected example output: expression == "B";

Current example output: expression == "||B";

What am I doing wrong?

Thanks for your time!

FisherPeak
  • 11
  • 4

1 Answers1

0

When you are using a string literal you should escape the backslash as well.. This should work:

fullVar1 = new RegExp("((\\||^)" + "(" + var1 + ")" + "(\\||$))");
//                       ^                              ^

JavaScript generally ignores backslash that don't escape a special character. This can be easily demonstrated like this:

console.log("Backslash is ignored:", "\|")
console.log("Backslash is properly escaped:", "\\|")
Kobi
  • 135,331
  • 41
  • 252
  • 292