DEV
DEV

Reputation: 2176

Regular Expression is not working with string name

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

Upvotes: 2

Views: 46

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382464

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).

Upvotes: 4

Related Questions