简体   繁体   中英

Using split/join to replace a string with an array

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"));

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.

Split uses regular expressions, so

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

If you are trying to replace a string:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM