views:

52

answers:

2

hi everyone!

i here a Work and i don't know how to do it. i have a string here:

<div class="demotext">
   <p>this is demo string i demo want to demo use</p>
</div>

i create the array variable for demo:

var demoarray = new array('a','b','c');

now i want replace 'demo' in string by array node, follow 'demo' one change to 'a' , 'demo' two change to 'b'....

+4  A: 
var string = 'this is demo string i demo want to demo use';
var demoarray = ['a','b','c'];

for(i=0; i < demoarray.length; i++){
    string = string.replace('demo',demoarray[i] );
}

alert(string) // "this is a string i b want to c use"
vsync
how to do if i want to using regex to select text 'demo' in this string :)
Rueta
why with Regex?
vsync
because the text i want to select maybe diffirent character and only select by a Regex. and if my data array is a mult-dimensional array ?example: 'demo' one change to array[0][1] . 'demo' two change to array[1][1] ....
Rueta
well then, my solution isn't very scalable, but did what you've asked. for a 2D array you would need an extra nested loop.
vsync
A: 

.

function sequential_replace(str, replacementRx, arr) {
   var i = 0;
   return str.replace(replacementRx, function() {
      return arr[i++];
   });
}

return sequential_replace("this is demo string i demo want to demo use",
                          /demo/g, ['a', 'b', 'c']);
KennyTM
'return sequential_replace' -> you don't need the last 'Return', justsequential_replace(...)
vsync