2

I have a Regular Expression in javascript that is not working. My code is...

JavaScript :

  function doit()
  {
     var string="something";
     var el=document.getElementById("monu");
     el.innerHTML = el.innerHTML.replace(/(string)/ig,"Everything");
  }

HTML :

    <div id="monu">something is better than nothing</div>
    <button onclick=doit();>replace</button>

In function replace if I am using string as pattern it is not working. How can I make it work...any suggestion..

DEV
  • 2,106
  • 3
  • 25
  • 40

1 Answers1

4

Use the RegExp constructor :

el.innerHTML = el.innerHTML.replace(new RegExp(string,'ig'),"Everything");

Note that if you want to replace a string containing special regex patterns without interpreting them as regex patterns (for example you want to replace exactly ".*"), then you need to escape your string. There's unfortunately no standard function in JavaScript for that but it's easy to write and find (here's one).

Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Thanks for quick reply, I have one more question suppose I have to replace it with string1 where string1="Everything", what shoud i do in this case..? – DEV Jan 29 '14 at 13:24
  • Nice. But, if possible, I would skip the string var and create the var as a RegExp immediatly, to avoid what dystroy mentions in the note. I.e. `var theRE = new RegExp('something', 'ig'); ... el.innerHTML = el.innerHTML.replace(theRE,"Everything");`. This also allows you to reuse the regex at lower cost (performance wise). – SamWhan Jan 29 '14 at 13:34