最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using splitjoin to replace a string with an array - Stack Overflow

programmeradmin7浏览0评论

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

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"));
Share Improve this question edited Jul 6, 2019 at 16:02 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Jun 22, 2011 at 15:21 Gustavo PortoGustavo Porto 2242 gold badges4 silver badges13 bronze badges 3
  • 1 Please be clearer on what your trying to do. – Ash Burlaczenko Commented Jun 22, 2011 at 15:24
  • Please give an example of what item should contain when this has pleted. Should item look like zzzabc or zzzdefg or something else entirely? – WesleyJohnson Commented Jun 22, 2011 at 15:29
  • HMM return the string item '1' to -> 'zzz', or item '2' to -> 'xxx'... – Gustavo Porto Commented Jun 22, 2011 at 15:48
Add a ment  | 

2 Answers 2

Reset to default 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.

Split uses regular expressions, so

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

If you are trying to replace a string:

"abcdef".replace('abc','zzz') == "zzzdef"
发布评论

评论列表(0)

  1. 暂无评论