nicael
nicael

Reputation: 19024

Can't replace() using regex

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?

Upvotes: 0

Views: 89

Answers (2)

raina77ow
raina77ow

Reputation: 106483

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.

Upvotes: 6

user229044
user229044

Reputation: 239551

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

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

Upvotes: 5

Related Questions