Node.js一次替换多个字符串

时间:2016-04-01 07:40:39

标签: javascript node.js

如何一次更换多个字符串?例如,有如下代码:

// the 'content' is part of html, so it all addjoined, 
// but I delete some tags and sepeate tag to look clean
// *** the content is mongodb data

var content ='<p>ggfhjghgk<a class="mg-popup-img" href="/uploads/2016040117124079.png"><img class="pop" style="max-width: 100%; max-height: 100%;" src="/uploads/2016040117124079.png" /></a></p>

&#39;

我要做的是,将图片名称替换为新名称。所以每个文件名都不一样。像这样:

<p>ggfhjghgk<a class="mg-popup-img" href="/uploads/2016050117124079.png"><img class="pop" style="max-width: 100%; max-height: 100%;" src="/uploads/2016050117124079.png" /></a></p>
我用Google搜索,发现了几个博士。像这样:Replace multiple strings at once 所以我试着

String.prototype.replaceArray = function(find, replace) {
var replaceString = this;
for (var i = 0; i < find.length; i++) {
    replaceString = replaceString.replace(find[i], replace[i]);
}
    return replaceString;
};

var originals = ['20160401', '20160402', '20160403'];
var newnames = ['20160501', '20160502', '20160503'];

var newcontent = content.replaceArray(originals, newnames);
console.log(newcontent); // not working properly.-> It's not changed.

我怎么能这样做呢?实际上,我正在尝试实施“文章复制任务”。当用户复制文章时,如果文章有图像标签,我应该复制图像文件并将图像src替换为新文件。赞赏任何指示......谢谢。

1 个答案:

答案 0 :(得分:2)

如果它是一个字符串,你可以regex

&#13;
&#13;
// search for /uploads/(anything).png
var regex = /(\/uploads\/)(.+?)(\.png)/gi;
var counter = 0;
var str = '<img class="pop" src="/uploads/20160401.png" /><img class="pop" src="/uploads/20160402.png" /><img class="pop" src="/uploads/20160403.png" />';

// replace /uploads/(anything).png with /uploads/mynewfile(counter).png
var result = str.replace(regex, function () {
  var path = arguments[1],
      extension = arguments[3];

  return path + 'mynewfile' + (++counter) + extension;
});

console.log(str);
console.log(result);
&#13;
&#13;
&#13;