【问题标题】:Search a string for different words在字符串中搜索不同的单词
【发布时间】:2021-07-10 17:33:52
【问题描述】:

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

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 递增到

【问题讨论】:

    标签: javascript arrays typescript


    【解决方案1】:

    你应该了解looping

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

    【讨论】:

      【解决方案2】:

      在您的测试中,您是否尝试将与某些匹配的单词放在文本上?

      之后,将 RegExp 对象作为“replace”函数的第一个参数传递,并使用标志 'g' 来替换所有匹配项:

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

      如果你想匹配精确的单词(例如:“cat”不匹配“category”),表达式应该包含前一个和下一个字符:

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

      最后一组包含“?=”以确保下一个字符是空格或字符串结尾,但不要捕获它,以便在下一次匹配时可用,并且不会遇到连续单词的问题(像“猫猫”)。

      您还需要注意单词上的特殊字符,如果单词可以包含一些,则必须对其进行转义(参见Is there a RegExp.escape function in JavaScript?

      【讨论】:

        猜你喜欢
        • 2011-12-27
        • 1970-01-01
        • 2016-04-26
        • 1970-01-01
        • 2013-10-22
        • 1970-01-01
        • 2013-09-15
        相关资源
        最近更新 更多