gpt4 book ai didi

javascript - 如何替换js中的文本?

转载 作者:行者123 更新时间:2023-11-28 05:00:47 24 4
gpt4 key购买 nike

假设我有以下内容:

var s = "This is a test of the battle system."

我有一个数组:

var array = [
"is <b>a test</b>",
"of the <div style=\"color:red\">battle</div> system"
]

是否有一些函数或方法可以使我可以处理字符串 s 使得输出为:

var p = "This is <b>a test</b> of the <div style=\"color:red\">battle</div> system."

基于数组中的任意元素?

注意数组元素要按顺序执行。因此,查看数组 1 中的第一个元素,找到字符串“s”中“替换”的正确位置。然后查看数组元素 2,在字符串“s”中找到“替换”的正确位置。

请注意,该字符串可以包含数字、括号和其他字符,例如破折号(虽然没有 <>)

最佳答案

更新:在 Colin DeClue 的评论之后,我认为你想做一些与我原先想象的不同的事情。

这里是你如何做到这一点

//your array
var array = [
"is <b>a test</b>",
"of the <div style=\"color:red\">battle</div> system"
];
//create a sample span element, this is to use the built in ability to get texts for tags
var cElem = document.createElement("span");

//create a clean version of the array, without the HTML, map might need to be shimmed for older browsers with a for loop;
var cleanArray = array.map(function(elem){
cElem.innerHTML = elem;
return cElem.textContent;
});
//the string you want to replace on
var s = "This is a test of the battle system."

//for each element in the array, look for elements that are the same as in the clean array, and replace them with the HTML versions
for(var i=0;i<array.length;i++){
var idx;//an index to start from, to avoid infinite loops, see discussion with 6502 for more information
while((idx = s.indexOf(cleanArray[i],idx)) > -1){
s = s.replace(cleanArray[i],array[i]);
idx +=(array[i].length - cleanArray[i].length) +1;//update the index
}
}
//write result
document.write(s);

工作示例:http://jsbin.com/opudah/9/edit


原始答案,以防这毕竟是你的意思

是的。使用join

var s = array.join(" ");

Here is a working example in codepen

关于javascript - 如何替换js中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15669445/

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