How to use .replace() to replace parts of a string containing a bitwise operator

时间:2019-01-09 22:19:50

标签: javascript str-replace

I know you can use str.replace(/something/g, "something else") to replace all occurrences of a specific string. But if that string contains a bitwise operator, the code no longer works. It interprets ^ as an xor operator, so how do you work around this? How do you specify to look for the string ^, and not the operator ^?

var str = "3^3^3";
var newStr = str.replace(/^/g, "**"); //returns "**3^3^3"
console.log(eval(newStr)); //returns error

desired result:

var str = "3^3^3";
var newStr = something... // "3**3**3"
console.log(eval(newStr)); // 762597484987

1 个答案:

答案 0 :(得分:4)

Just escape the starting symbol.

/\^/g
 ^

var str = "3^3^3";
var newStr = str.replace(/\^/g, "**"); //returns "**3^3^3"
console.log(eval(newStr));