var string = "Please click on dashboard and then open the dashboard details to verify your details on the data";
var stringArray = ["dashboard" , "dashboard" , "data"]
var replaceArray = ["https://abcd.com/login" , "https://abcd.com/home" , "https://abcd.com/data"]
for(i=0;i<stringArray.length; i++){
string = string.replace(stringArray[i].trim(), "<a href='"+replaceArray[i].trim()+"'>"+stringArray[i].trim()+"</a>");
}我有一个字符串和上面的两个数组。我需要用两个数组中提到的相应的锚链接标记替换我的字符串。stringArray定义了要链接的单词,replaceArray定义了应该添加的URL。和第一次出现的仪表板一样,应该将仪表板锚定为"https://abcd.com/login“,第二次出现的”仪表板“应替换为"https://abcd.com/home”,而“数据”应替换为"https://abcd.com/data"“。
我试图找出字符串中的单词,并使用replace/replaceAll替换它,对于单个出现的单词可以很好地工作,但是对于多次出现,它是不工作的。
任何人都能帮我解决这个问题。
结果:
"Please click on <a href='https://abcd.com/login'><a href='https://abcd.com/home'>dashboard</a></a> and then open the dashboard details to verify your details on the <a href='https://abcd.com/data'>data</a>"预期输出:
"Please click on <a href='https://abcd.com/login'>dashboard</a> and then open the <a href='https://abcd.com/home'>dashboard</a> details to verify your details on the <a href='https://abcd.com/data'>data</a>"发布于 2022-07-05 10:35:46
这个人怎么样,
var string = "Please click on dashboard and then open the dashboard details to verify your details on the data";
const stringArray = string.split(' ');
var targetTexts = ["dashboard" , "dashboard" , "data"]
var replaceTexts = ["https://abcd.com/login" , "https://abcd.com/home" , "https://abcd.com/data"]
const resultArray = []
for (let i = 0; i < stringArray.length; i++) {
const word = stringArray[i];
const targetTextIndex = targetTexts.indexOf(word);
if (targetTextIndex > -1) {
resultArray.push("<a href='"+replaceTexts[targetTextIndex]+"'>"+word+"</a>")
targetTexts = targetTexts.filter((_el, idx) => idx !== targetTextIndex)
replaceTexts = replaceTexts.filter((_el, idx) => idx !== targetTextIndex)
} else {
resultArray.push(word);
}
}
console.log(resultArray.join(' '))我希望你在这件事上有个提示。它的工作就像一个魅力,会有异常处理为您处理。
https://stackoverflow.com/questions/72867805
复制相似问题