我有一些问题需要更换。
有一个段落,例如:
(*#*) <p>The video was posted on Facebook and shows a shirtless man repeatedly throwing rocks at a wombat as it tries to (*#*) run away.</p>
符号(*#*)
是需要替换新字符串的位置。
但是替换的就不一样了,会有图片,链接等等...
let photo = '<div class="photo"><img src="'+media+'"></div>'
let link = '<a class="relatednews" href="'+linkStr+'">'linkName'</a>'
替换内容按 json 顺序存储,我需要使用它们来替换 段落,例如:
<div class="photo"><img src="'+media+'"></div>
<p>The video was posted on Facebook and shows a shirtless man repeatedly throwing rocks at a wombat as it tries to <a class="relatednews" href="'+linkStr+'">'linkName'</a>' run away.</p>
我使用 for 和 replaceAt 无法处理这个问题。
replaceIndexAry
存储(*#*)
的位置。
console.log(replaceIndexAry)
//[ 0 , 118 ] it's store the every (*#*) index in the paragraph;
for(var j=0;j<data.length;j++){
if(itype === 'photo'){
mediaStr = self.replaceAt(paragraph,replaceIndexAry[j],photo)
}else if(itype === 'link'){
mediaStr = self.replaceAt(paragraph,replaceIndexAry[j],link)
}
}
function replaceAt( origin, index, replacement){
return origin.substr(0, index) + replacement+ origin.substr(index + replacement.length);
}
结果将是:
(*#*) <p>The video was posted on Facebook and shows a shirtless man repeatedly throwing rocks at a wombat as it tries to <a class="relatednews" href="'+linkStr+'">'linkName'</a>' run away.</p>
我无法成功替换所有项目,如何将paragraph中的所有(*#*)
替换为按顺序替换数据?
p.s. The all data( include paragraph and replacement) are given by Back-end, the API could not be changed, and the Back-end asked me follow this logic.
最佳答案
let data='(*#*) <p>The video was posted on Facebook and shows a shirtless man repeatedly throwing rocks at a wombat as it tries to (*#*) run away.</p>';
let photo = '<div class="photo"><img src="media"></div>';
let link = '<a class="relatednews" href="linkStr">linkName</a>';
data = data.replace('(*#*)', photo);
data = data.replace('(*#*)', link);
它会给你:
"<div class=\"photo\"><img src=\"media\"></div> <p>The video was posted on Facebook and shows a shirtless man repeatedly throwing rocks at a wombat as it tries to <a class=\"relatednews\" href=\"linkStr\">linkName</a> run away.</p>"
在数据变量中,如果我正确理解你的问题。
关于Javascript按位置用不同的字符串替换相同的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58229546/