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?

2 Answers 2

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.

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

2 Comments

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.
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!
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");

Comments

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.