5

I'm trying to replace the value of item with values ​​in the array arr, but I only get that if I use: arr [1], arr [2] ... if I just let arr, returns abcdefg.

I am PHP programmer, and I have a minimal notion with JavaScript, can someone give me a light?

var item = 'abcdefg';
var arr = new Array();
arr[1] = "zzz";
arr[2] = "abc";
var test = item.split(arr);
alert(test.join("\n"));
3
  • 1
    Please be clearer on what your trying to do. Commented Jun 22, 2011 at 15:24
  • Please give an example of what item should contain when this has completed. Should item look like zzzabc or zzzdefg or something else entirely? Commented Jun 22, 2011 at 15:29
  • HMM return the string item '1' to -> 'zzz', or item '2' to -> 'xxx'... Commented Jun 22, 2011 at 15:48

2 Answers 2

8

Use:

var item = 'Hello, 1, my name is 2.';
var arr = new Array();
arr [1] = 'admin';
arr [2] = 'guest';
for (var x in arr)
    item = item.replace(x, arr[x]);
alert(item);

It produces:

Hello, admin, my name is guest.
Sign up to request clarification or add additional context in comments.

7 Comments

What I'm trying to do is replace the IDs with names, example: id 1 - admin id 2 - guest id 3 - test1 id 4 - test2 These values​​, I would have in an array (arr [1] = admin, arr [2] = guest, etc.), the string value item, would be the id, so I searched the id in the array array and replace the name .
you may need to do foreach item in array, do replacement.
can you help me with this? :(
@GtOkAi, I added some code. Is that what you're looking for?
Yes! Exactly! It would only be to the contrary, changing the admin change by 1 and 2 per guest
|
2

Split uses regular expressions, so

"My String".split('S') == ["My ","tring"]

If you are trying to replace a string:

"abcdef".replace('abc','zzz') == "zzzdef"

2 Comments

It uses regular expressions, i.e. /[a-z]+/ or strings, i.e. "/[a-z]+/". The former splits on any block of lower-case letters, the latter on the literal string /[a-z]+/.

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.