首页 > 解决方案 > 在字符串中搜索不同的单词

问题描述

我需要搜索一个字符串以检查它是否包含存储在数组中的特定单词。如果字符串包含数组中的单词,则必须突出显示这些单词。在进入突出显示部分之前,如果找到数组中的单词,我尝试用虚拟文本替换字符串。代码如下:

let words:String[]=['cat','rat','bat'];
let text: String = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
var newText = text.replace(words[0],"TEST");

所以 replace 方法中的单词数组应该从 0 递增到 < words.length。谁能建议一种方法来做到这一点?

标签: javascriptarraystypescript

解决方案


您应该了解循环

let words:String[] = ['cat','rat','bat'];
let text: String = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."

let modifiedText = text;

words.forEach(word => {
  modifiedText = modifiedText.replace(word,"TEST");
});

推荐阅读