简体   繁体   English

内部 html 替换为括号中的文本

[英]Inner html replace with text in brackets

I am able to replace this text -->>我可以替换此文本 -->>

"querying policy failed: No such file or directory" fine to "HELLO" . "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>")

But I want to replace this text -->> "querying policy failed: No such file or directory (2)" , which is not happening due to text in brackets -> (2).但我想替换此文本 -->> "querying policy failed: No such file or directory (2)" ,由于括号中的文本 -> (2) 而不会发生这种情况。

Below code doesnt work.下面的代码不起作用。

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>")

Any suggestions , how to replace任何建议,如何更换

querying policy failed: No such file or directory (2) to HELLO . querying policy failed: No such file or directory (2) to HELLO

You must escape the parenthesis by inserting \\ before them, as they are reserved characters used for capturing groups.您必须通过在括号前插入\\来转义括号,因为它们是用于捕获组的保留字符。

You can learn more about RegExp capturing groups in Groups and ranges - JavaScript |您可以在Groups and Ranges 中了解更多关于 RegExp 捕获组的信息- JavaScript | MDN and about character escaping in this question . 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)

Ref: https://stackoverflow.com/a/9115461/1171702参考: https : //stackoverflow.com/a/9115461/1171702

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM