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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.