简体   繁体   中英

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

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

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 .

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 | MDN and about character escaping in this question .

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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