js replace替换问题

var arr = ['a','b','c','d'];

var t = "<img src='' id='111'><img src='' id='man'><img src='' id='is'><img src='' id='u'>";

如何把 t 变成 "<img src='' id='a'><img src='' id='b'><img src='' id='c'><img src='' id='d'>"

侃侃无极
浏览 365回答 1
1回答

HUX布斯

我照着你上一个问题的直接改一下就可以了我这么理解题意,就是字符串里的id依次改成arr数组里对应的元素,那么在全局正则匹配的时候,在外部用一个变量标识数组的索引,每次替换就自增1,就可以了。var arr = ['a','b','c','d'];var i = 0;var t = "<img src='' id='good'><img src='' id='man'><img src='' id='is'><img src='' id='u'>";&nbsp; &nbsp; t = t.replace(/id='(\w*)'/g,function(match,$1,index){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(match,$1,index);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "id='"+ arr[i++]+"'";&nbsp; &nbsp; })
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript