简体   繁体   English

用 javascript 中的不同单词替换每个出现的字符/单词

[英]Replace each occurrence of character/word with different word in javascript

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>"); }

I have a string and 2 arrays like above.我有一个 string 和 2 个 arrays 像上面一样。 I need to replace my string with respective anchor link tags as mentioned in two arrays.我需要用两个 arrays 中提到的相应锚链接标签替换我的 string。 stringArray defines the word to be linked and replaceArray defines the URL should be added. stringArray 定义要链接的单词,replaceArray 定义应添加的 URL。 Like first occurrence of dashboard should be anchor linked with "https://abcd.com/login" and second occurance of "dashboard" should be replaced with "https://abcd.com/home" and "data" should be replaced with "https://abcd.com/data".就像仪表板的第一次出现应该锚链接到“https://abcd.com/login”和“仪表板”的第二次出现应该替换为“https://abcd.com/home”和“数据”应该替换与“https://abcd.com/data”。

I tried to find out the word in string and replace it using replace/replaceAll, working fine for single occurrence word, but for multiple occurrences it is not working.我试图找出 string 中的单词并使用 replace/replaceAll 替换它,对于单个出现的单词工作正常,但对于多次出现它不起作用。

Anyone help me to resolve this.任何人都可以帮我解决这个问题。

Resulting:结果:

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

Expected Output:预期 Output:

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

I propose to solve this problem using the reduce method and a regular expression, where the regular expression will be the n-element of the stringArray array.我建议使用 reduce 方法和正则表达式来解决这个问题,其中正则表达式将是 stringArray 数组的 n 元素。

Through reduce, we will achieve that by replacing the word in the variable "string" at each iteration, for the next iteration we will already replace the changed value of the variable "string"通过reduce,我们将通过在每次迭代时替换变量“string”中的单词来实现这一点,对于下一次迭代,我们已经替换了变量“string”的更改值

Solution:解决方案:

 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 = ["apple collection", "delta collection", "data collection"]; stringArray.reduce((acc, stringRegExp, index) => { return acc.replace(new RegExp(stringRegExp), replaceArray[index]); }, string)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM