[英]JavaScript remove double brackets (with inner text) from HTML block element
[英]Inner html replace with text in brackets
我可以替换此文本 -->>
"querying policy failed: No such file or directory"
对"HELLO"
很好。
document.body.innerHTML = document.body.innerHTML.replace(
/querying policy failed: No such file or directory /g,
"<span style='color:black;background-color:#ABB2B9'>HELLO</span>")
但我想替换此文本 -->> "querying policy failed: No such file or directory (2)"
,由于括号中的文本 -> (2) 而不会发生这种情况。
下面的代码不起作用。
document.body.innerHTML = document.body.innerHTML.replace(
/querying policy failed: No such file or directory (2)/g,
"<span style='color:black;background-color:#ABB2B9'>HELLO</span>")
任何建议,如何更换
querying policy failed: No such file or directory (2)
to HELLO
。
您必须通过在括号前插入\\
来转义括号,因为它们是用于捕获组的保留字符。
您可以在Groups and Ranges 中了解更多关于 RegExp 捕获组的信息- JavaScript | MDN和关于这个问题中的字符转义。
document.querySelector('p').innerHTML = document.querySelector('p').innerHTML.replace(/querying policy failed: No such file or directory \\(2\\)/g, '<span style="color: black; background-color: #ABB2B9">HELLO</span>');
<p>querying policy failed: No such file or directory (2)</p>
// escape the parentheses with backslashes directly in the string. //document.body.innerHTML = document.body.innerHTML.replace( // /querying policy failed: No such file or directory \\(2\\)/g, // "HELLO"); // in two steps. // 1. remove the parens; // 2. remove the rest of the string. document.body.innerHTML = document.body.innerHTML .replace(/[()]/g, "") .replace(/querying policy failed: No such file or directory 2/g, "HELLO");
querying policy failed: No such file or directory (2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.