0

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'....

2
  • Can you clarify the question a bit? You want to convert "demo" to "abcd"? (Also, you have a syntax error: It's new Array, not new array [or better yet, just use var demoarray = ['a', 'b', 'c'];]). Commented May 13, 2010 at 8:30
  • oh thankyou. i type wrong 'Array' ^^. i want convert "demo" firse to "a" and the same in "demo" continues width "b" "c" and "d" Commented May 13, 2010 at 9:03

2 Answers 2

4
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"
Sign up to request clarification or add additional context in comments.

3 Comments

how to do if i want to using regex to select text 'demo' in this string :)
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] ....
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.
0

.

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']);

1 Comment

'return sequential_replace' -> you don't need the last 'Return', just sequential_replace(...)

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.