-3

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.

wazz
  • 4,953
  • 5
  • 20
  • 34

2 Answers2

0

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>
  • Nice. Now sure why it was not working yesterday. i think i tried that way. But still you solved the issue. thanx – ahmad82pkn Jul 28 '21 at 05:30
0

// 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

wazz
  • 4,953
  • 5
  • 20
  • 34