【问题标题】:Apply array of string with string.replace使用 string.replace 应用字符串数组
【发布时间】:2017-06-01 10:14:06
【问题描述】:

假设我有一个这样的字符串:

const sentence = "This is my custom string";

我想突出显示这句话中输入字段的单词。

假设用户输入了一个字符串,我已经将单独的单词转换为一个数组,如下所示:

["custom", "string", "is"]

我知道想用数组中单词的突出显示版本替换句子中的单词。对于一个单词,我会这样做:

const word = 'custom';

const searchFor = new RegExp(`(${word})`, 'gi');
const replaceWith = '<strong class="highlight">$1</strong>';

const highlightedSentence = sentence.replace(searchFor, replaceWith);

如何将这个带有数组的逻辑应用于整个句子?

我不能简单地循环遍历它,因为字符串将包含我突出显示的类,这也将被带入第二个循环、第三个循环等的突出显示过程中。

这意味着如果用户在第二个循环中输入:

"high custom"

我会突出显示我突出显示的课程,从而导致突出显示 inception。

举个例子,我的意思是尝试注释/取消注释 2 个荧光笔功能:

https://jsfiddle.net/qh9ttvp2/1/

【问题讨论】:

    标签: javascript arrays string ecmascript-6


    【解决方案1】:

    您的问题是,在替换单词时,您将已添加的 html 标记替换为 .class 'highlight'。

    这里的解决方案可能是替换任何不是 html 标记的内容。在您的 jsfiddle 示例中替换此行。

    const searchFor = new RegExp(`(${word})(?!([^<]+)?>)`, 'gi');
    

    【讨论】:

    • 谢谢,从来不知道这可以用正则表达式来实现。是时候深入研究一下正则表达式了。像魅力一样工作。
    【解决方案2】:

    您可以将句子拆分为数组并检查您的元素是否已突出显示:

    let sentence = "This is a some type of long string with all kinds of words in it, all kinds.";
    let sentenceArr = sentence.split(' '); // make an array 
    const query = "kinds words all type";
    
    function highlighter(query, sentence) {
      const words = query.match(/\S+/g);
    
      words.forEach((word) => {
          // Create a capture group since we are searching case insensitive.
          const searchFor = new RegExp(`(${word})`, 'gi');
          const replaceWith = '<strong class="highlight">$1</strong>';
          sentenceArr = sentenceArr.map(sw => (sw.indexOf('strong class="highlight"') === -1) ? sw.replace(searchFor, replaceWith) : sw); // if already highlited - skip
          //sentence = sentence.replace(searchFor, replaceWith);
      });
      
      // console.log(sentence);
    
      document.querySelector('.highlighted-sentence').innerHTML = sentenceArr.join(' '); // notice sentenceArr
    }
    
    // Works.
    //highlighter('kinds words all type', sentence);
    
    // Doesn't work.
    highlighter('kinds words high', sentence);
    &lt;div class="highlighted-sentence"&gt;&lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 2019-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 2019-12-04
      • 1970-01-01
      相关资源
      最近更新 更多