gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:49:03 24 4
gpt4 key购买 nike

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

// 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>

'

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

<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>

我用谷歌搜索,找到了几个文档。像这样: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 替换为新文件。感谢任何指点...谢谢。

最佳答案

如果它是一个字符串,您可以对其进行正则表达式:

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

关于javascript - Node.js 一次替换多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36350671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com