-1

I'm trying to replace the word hello anywhere on the page with the word hi using Javascript. I created the script below however it isn't working how anticipated, is there something that I can do to achieve the outcome desired.

function(data) {
            var newdata = data.replace("hello", "hi");
}

Jsfiddle

2 Answers2

2

In your example, you are only replacing the first occurence.

Below the JavaScript documentation about replace:

Note: If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier.

You have to use the global modifier as below

function(data) {
             var newdata = data.replace(/hello/g,"hi");
}
Radouane ROUFID
  • 10,595
  • 9
  • 42
  • 80
  • 1
    I updated the fiddle using your code however it's not changed anything. https://jsfiddle.net/3ncveq90/3/ fiddle link –  Jun 29 '16 at 00:12
  • The replaced content is now in the variable _newdata_ you have to use it to do whatever you want. In the fiddle example you gave me you do nothing with it. – Radouane ROUFID Jun 29 '16 at 00:15
2

This will work, although might be overkill using regular expressions:

document.body.innerHTML = document.body.innerHTML.replace(/hello/g, "hi")

Jsfiddle

  • 1
    would using document.body.innerHTml.replace be the best way to do this if I had 200 of these one after another, replacing alot of words on the a page? –  Jun 29 '16 at 00:14
  • I'm not sure this is the best way. I know there are many ways to do this that get more complex. But I tested it in jsfiddle with 200 instances of 'hello' and it changed them all to 'hi' with no issues. Hope this helps a bit. – John Wilson Jun 29 '16 at 00:28