Using split / join to replace a string with an array

I am trying to replace the value itemin the values in the array arr, but I get it, but if I use: arr [1], arr [2]... if I just let arrreturns abcdefg.

I am a PHP programmer and I have a minimal understanding of JavaScript, can someone tell me?

var item = 'abcdefg';
var arr = new Array();
arr[1] = "zzz";
arr[2] = "abc";
var test = item.split(arr);
alert(test.join("\n"));
+5
source share
2 answers

Using:

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.
+9
source

Split uses regular expressions, therefore

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

If you are trying to replace the string:

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

All Articles