1

is my syntax correct i wanted to replace string in pattern abcd+abcd+ but its not working using replace method in JavaScript here is the code snapshot the commented one dose not work which i require

function myFunction() {
  var str = document.getElementById("demo").innerText;
  //var res = str.replace(/+/g, "red");
  var res2 = str.replace("+", "red");
  document.getElementById("demo").innerText = res2;
}
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<p id="demo">Mr + has a + house and a blue car.</p>
<button onclick="myFunction()">Try it</button>
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55

1 Answers1

2

The commented-out portion is nearly right, but you need to escape the + because it's a special character in regular expressions:

function myFunction() {
  var str = document.getElementById("demo").textContent;
  var res = str.replace(/\+/g, "red");
  document.getElementById("demo").textContent= res;
}
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<p id="demo">Mr + has a + house and a blue car.</p>
<button onclick="myFunction()">Try it</button>

innerText is a quirky nonstandard property that IE introduced. It is highly recommended to instead use the standard, quicker, more reliable textContent instead - see http://perfectionkills.com/the-poor-misunderstood-innerText

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320