-1

I get it to work on just replacing one instance with this code:

var someString = ['He', 'Test', 'of'];
var x = 0;
for (i = 0; i < 2; i++) {
    document.body.innerHTML = document.body.innerHTML.replace(''+someString[i]+'', 'text');
}

How to get it to replace all the instances? I tried this:

/+someString[x]+/g 
/'+someString[x]+'/g

since using a normal string, /Test/g would work how to i format it when the string is a variable string.

user3711421
  • 1,658
  • 3
  • 20
  • 37
  • why you do not manipulate string in the loop and then reappend it back to the body? – eded Dec 09 '14 at 21:05
  • Yes, was duplicate. First time im trying javascript have no clue what to search for. This is for an android app, and i only need this small snipped in javascript. Thanks for all answers, so many so fast, not used to over in the android part. – user3711421 Dec 09 '14 at 21:19
  • Use `someString.length` rather that hardcoding 2. `someString.length` is actually 3 in this case. – tachyonflux Dec 09 '14 at 21:24
  • They are not really related, i just made it like this for the example. In the bigger program it will loop through much more times. – user3711421 Dec 09 '14 at 21:26

3 Answers3

1

Use new RegExp to create a regular expression from a string:

for (i = 0; i < 2; i++) {
    var re = new RegExp(someString[x], 'g')
    document.body.innerHTML = document.body.innerHTML.replace(re, 'text');
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You can use new RegExp

var Replace = ['He', 'Test', 'of'];
for (var = 0;i<String.length;i++) {

var search = Replace[i];
var regEx = new RegExp(search, "g");
var replaceMask = 'text';

var result = 'Test He of where Test he of so'.replace(regEx, replaceMask);
document.body.innerHTML = result;
}
baao
  • 71,625
  • 17
  • 143
  • 203
0

try this

var someString = ['He', 'Test', 'of'];
var x = 0;
for (i = 0; i < 2; i++) {
    document.body.innerHTML = document.body.innerHTML.replace(new RegExp(someString[i],"g"), 'text');
}
  • Choosing this answer for the simplicity. Writing this for a webview in an android app where the java script is in a long string and this method requires little formating. Thanks – user3711421 Dec 09 '14 at 21:24