在字符串中搜索不同的单词

nkhmeac6  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(306)

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

  1. let words:String[]=['cat','rat','bat'];
  2. 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."
  3. var newText = text.replace(words[0],"TEST");

因此,replace方法中的单词数组应该从0增加到<words.length。有人能建议一种方法吗?

r7knjye2

r7knjye21#

你应该学习循环。

  1. let words:String[] = ['cat','rat','bat'];
  2. 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."
  3. let modifiedText = text;
  4. words.forEach(word => {
  5. modifiedText = modifiedText.replace(word,"TEST");
  6. });
z8dt9xmd

z8dt9xmd2#

在你的测试中,你有没有试着在文本中加入一些匹配的单词?
之后,将一个regexp对象作为“replace”函数的第一个参数传递,并使用标志“g”替换所有出现的情况:

  1. var newText = text;
  2. for (let i in words) {
  3. newText = newText.replace(new RegExp(words[i], 'g'),"TEST");
  4. }

如果要匹配精确的单词(例如,“cat”不匹配“category”),表达式应包括上一个字符和下一个字符:

  1. newText = newText.replace(new RegExp('(^|\\s)'+words[i]+'(?=\\s|$)', 'g'),"$1TEST");

最后一个组包含“?=”以确保下一个字符是字符串的空格或结尾,但不捕获它,以便在下一次匹配时可用,并且不会遇到连续单词的问题(如“cat”)。
您还需要注意单词上的特殊字符,如果单词可能包含一些字符,则必须对其进行转义(请参阅javascript中是否有regexp.escape函数?)

相关问题