首页 > 解决方案 > 在 Javascript 替换中写括号

问题描述

function myFunction() {
  var text = document.getElementById("ansiText").value; 
  var finalText = text.replace(/)/g, "right");
 
  document.getElementById("ansiText").value = finalText;
}

我想查找和替换(asleft)as right。但是如果我在代码中编写)它不起作用,它会产生错误。我该如何写(在替换功能中?

标签: javascripthtmljqueryweb

解决方案


只需转义括号即可解决此问题:text.replace(/\)/g, "right")

function myFunction() {
  var text = document.getElementById("ansiText").value; 
  var finalText = text.replace(/\)/g, "right");
 
  document.getElementById("ansiText").value = finalText;
}

推荐阅读