-1

I have been trying to do a simple replace using regex as see below. I was following this and this. But for some reason the code below just does not work. I honestly can't see what I did wrong.

  var equ = "77^7x";
  var base = "77";
  var exp = "7x";
  var output = equ;
  var replace = base + "^" + exp;
  var regex = new RegExp(replace, "gi");
  var newOutput = output.replace(regex, "Math.pow(" + base + "," + exp + ")");
  console.log(newOutput);

The output is not Math.pow(77^7x) as expected

I am using the python regex library
Filtered
  • 65
  • 1
  • 8

2 Answers2

1

^ is a regex metacharacter. You have to add a backslash. However, since you are converting from a string, you have to add 2 backslashes, one as the backslash, and another one to escape the backslash.

var equ = "77\^7x";
var base = "77";
var exp = "7x";
var output = equ;
var replace = base + "^" + exp;
var regex = new RegExp(replace, "gi");
var newOutput = output.replace(regex, "Math.pow(" + base + "," + exp + ")");
console.log("Regex: %o", regex);
console.log("String searched: Math.pow(" + base + "," + exp + ")");
console.log("Output: ", newOutput);

console.log("Does the backslash at the ^ make a difference?")

var replace = base + "\\^" + exp;
var regex = new RegExp(replace, "gi");
var newOutput = output.replace(regex, "Math.pow(" + base + "," + exp + ")");
console.log("Regex: %o", regex);
console.log("String searched: Math.pow(" + base + "," + exp + ")");
console.log("Output: ", newOutput);

As you can see, the regex is not present inside the string "Math.pow(77,7x)", so it does not match or replace anything.

Endothermic_Dragon
  • 1,147
  • 3
  • 13
1

JSFiddle: https://jsfiddle.net/DariusM/1zy3sf9h/2/

As someone else mentioned, the ^ character is a special character in Regexp, therefore it needs to be escaped. Use:

var regex = new RegExp(base + "\\^" + exp, "gi");
Darius
  • 61
  • 1
  • 5