Javascript 使用 split/join 用数组替换字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6442327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using split/join to replace a string with an array
提问by Gustavo Porto
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
.
我试图item
用数组中的值 ??替换 的值arr
,但我只有在使用时才能得到它:arr [1]
, arr [2]
... 如果我只是让
arr
, 返回abcdefg
。
I am PHP programmer, and I have a minimal notion with JavaScript, can someone give me a light?
我是 PHP 程序员,我对 JavaScript 有一个最小的概念,有人可以给我一个提示吗?
var item = 'abcdefg';
var arr = new Array();
arr[1] = "zzz";
arr[2] = "abc";
var test = item.split(arr);
alert(test.join("\n"));
回答by agent-j
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.
回答by Justin Thomas
Split uses regular expressions, so
Split 使用正则表达式,所以
"My String".split('S') == ["My ","tring"]
If you are trying to replace a string:
如果您尝试替换字符串:
"abcdef".replace('abc','zzz') == "zzzdef"