-1

In the following code, I am trying to replace multiple addition signs in a string with a single addition sign using Javascript. I am not getting the right regex expression for this please help!

Example: This++is+my+++++text --> This+is+my+text

Code:

function doThis(){
document.getElementById("result").value = document.getElementById("TextInput").value.replace(/++/g,'+');
}
<html>
<head>
</head>
<body>

<textarea type="number" autocomplete="off" cols="30" id="TextInput" name="message" rows="10" style="width: 100%;">This++is+my+++++text</textarea><br><br>

<input class="button" type="button" value="Press" onclick="doThis()"><br/><br/>

Result: <input type="text" id="result">

</body>
</html>
Cornelius Roemer
  • 3,772
  • 1
  • 24
  • 55
santosh
  • 742
  • 8
  • 19
  • 1
    What about using [`/\+{2,}/gm`](https://jex.im/regulex/#!flags=m&re=%5C%2B%7B2%2C%7D)? – evolutionxbox Jul 10 '21 at 22:55
  • 1
    Does this answer your question? [What special characters must be escaped in regular expressions?](https://stackoverflow.com/questions/399078/what-special-characters-must-be-escaped-in-regular-expressions) – Ivar Jul 10 '21 at 23:01

1 Answers1

2

You need to escape the +.

function doThis() {
  document.getElementById("result").value =
    document.getElementById("TextInput").value.replace(/\++/g, '+');
}
<textarea type="number" autocomplete="off" cols="30" id="TextInput" name="message" rows="10" style="width: 100%;">This++is+my+++++text</textarea><br><br>
<input class="button" type="button" value="Press" onclick="doThis()"><br/><br/> Result: <input type="text" id="result">
Unmitigated
  • 76,500
  • 11
  • 62
  • 80