0

I stuck for a while on a replace function. basically it works, but it does not work with brackets ().

I have prepared a fiddle for that:

jsfiddle.net/99xPY/3/

Markup:

<span>Textarea / Longtest</span><br>
<input id="textarea_1" type="text" size="30" maxlength="30" value="12()1212">

<br><br><br>

<span>String to replace</span><br>
<input id="textarea_2" type="text" size="30" maxlength="30"><br>

<span>Replacing String</span><br>
<input id="textarea_3" type="text" size="30" maxlength="30">

<input type="button" value="execute" onclick="replace()">

Javascript:

function replace(){
    var longtext = document.getElementById('textarea_1').value
    var StringToReplace = document.getElementById('textarea_2').value
    var UserReplacingString = document.getElementById('textarea_3').value;
    var oldWordRegEx = new RegExp(StringToReplace,'g');
    var result = longtext.replace(oldWordRegEx,UserReplacingString);

    alert(result);    
}

So enter 1 in the second box and a random value in third box. My JavaScript code replaces automatically all 1's in the first box, but it does not replace ( or ).

Can somebody help me with this problem please?

I have to use pure JavaScript (OnClick) and not jQuery or similar.

keenthinker
  • 7,645
  • 2
  • 35
  • 45

2 Answers2

2

( and ) are special characters for a Regex. You need to escape them. Your code used with \(\) instead works.

gretro
  • 1,934
  • 15
  • 25
2

Some characters have special meaning in regular expressions, so you must escape them.

According to this answer, you must escape the characters .^$*+?()[{\|.

To escape, add \ before them, but note you must also escape \ inside a string, so you need \\:

StringToReplace.replace(/[.^$*+?()[{\|]/g, '\\$&');

Demo

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • @user3482484 See the edited answer, the escaping method I first proposed wasn't correct. – Oriol Apr 01 '14 at 14:54