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
答案 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));