0

I want to replace all "w" with "e":

var d = document.getElementById('hash').innerHTML.replace("/w/g","e");

But it doesn't replace anything! Earlier I tried using replace("w","e"), but it replaced only the first "w".
So, what to do?

nicael
  • 18,550
  • 13
  • 57
  • 90

2 Answers2

6

If you actually want to modify the content (innerHTML) of an element (the original version of your question made it very likely), you should use this:

var el = document.getElementById('hash');
el.innerHTML = el.innerHTML.replace(/w/g, 'e');

... as replace (as any other string method) doesn't change the operated string in place - instead it creates a new string (result of replacement operation) and returns it.

If you only want to make a new, transformed version of the element's contents, the only change should be using proper regex object, written either with regex literal (delimited by / symbols) or with new RegExp(...) construct. In this particular case the latter would definitely be an overkill. So just drop the quotes around /w/g (already done in the code snippet above), and you'll be fine. )

As for '....replace('w', 'e') does replace only once...' part, that's actually quite a common gotcha: when used with a string as the first argument, .replace() will do its work no more than once.

Community
  • 1
  • 1
raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • 2
    Seemed like this is what they wanted, but turns out to be a poorly written question. They've since updated OP to be `var d =`, making it seem like they do in fact want a string. – Sam Apr 09 '14 at 15:13
  • I know how replace works. I wrote, that earlier I tried using replace("w","e"), but it REPLACED only the first "w". But I forgot that regex mustn't be put in quotes! – nicael Apr 09 '14 at 15:19
5

You're giving replace a string instead of a regex. Use a real regex:

var d = document.getElementById('hash').innerHTML.replace(/w/g,"e");
user229044
  • 232,980
  • 40
  • 330
  • 338