【问题标题】:How to compare string with array of words and highlight words in string that match?如何将字符串与单词数组进行比较并突出显示字符串中匹配的单词?
【发布时间】:2017-09-08 19:57:49
【问题描述】:

我有这个问题,我有很多这样的词

let words = ['prueba', 'etiquetas'];

和我的字符串

let product = 'Prueba de etiquetas';

这个单词数组和字符串总是不同的,每个产品都包含自己的单词数组,我想知道这些单词中有哪些在字符串中并在字符串中突出显示这些单词,在这种情况下,当我想打印productvariable,输出应该是:

Prueba礼节

到目前为止我的代码是这样的

if (words.length) {

    for (let x = 0; x < words.length; x++) {

        if (product.toUpperCase().indexOf(words[x].toUpperCase()) !== -1) {

            //Here I need to hightligh the words in the string
        }
    }
}

但我不知道如何在 product 变量中进行更改,有什么想法吗?难道我做错了什么?希望您能帮帮我,谢谢。

【问题讨论】:

  • @hellcode HTML.

标签: javascript arrays string


【解决方案1】:

将数组转换为正则表达式,并使用String#Replace 将单词用 span 换行:

const words = ['prueba', 'etiquetas'];
const product = 'Prueba Pruebaa de etiquetas aetiquetas';

// convert the array to a regular expression that looks for any word that is found in the list, regardless of case (i), over all the string (g)
const regexp = new RegExp(`\\b(${words.join('|')})\\b`, 'gi');

// replace the found words with a span that contains each word
const html = product.replace(regexp, '<span class="highlight">$&</span>');

demo.innerHTML = html;
.highlight {
  background: yellow;
}
&lt;div id="demo"&gt;&lt;/div&gt;

【讨论】:

  • 您可以通过标准替换省略替换功能:const html = product.replace(regexp, '&lt;span class="highlight"&gt;$&amp;&lt;/span&gt;');
  • 您可能希望在将每个单词连接在一起之前使用单词边界 \b 说明符包装每个单词,以免意外检测到不相关的单词部分:words.map(word =&gt; `\\b${word}\\b`).join('|')
  • @PatrickRoberts - 好主意,但您也可以使用 \\b(${words.join('|')})\\b 跳过地图。
【解决方案2】:

这是一个没有正则表达式的解决方案:

let words = ['prueba', 'etiquetas'];
let product = 'Prueba de etiquetas';

words = words.map(function(word) { return word.toLowerCase(); });

product = product.split(' ').map(function(word) { 
             return words.indexOf(word.toLowerCase()) >= 0 ? '<b>'+word+'</b>' : word; 
          }).join(' ')

console.log(product);

【讨论】:

  • 我喜欢这个答案,但我首先用@OriDrori 的答案解决了我的问题,谢谢。
  • 这个答案真的很有用,也很容易理解。谢谢@ivo
【解决方案3】:

你可以使用正则表达式:

var words   = ["product", "words"],
    product = "This arrAy of wOrds aNd String wiLl be dIFferent all tiMe, evEry pRoduCt conTaiNs its own arRay oF words.";
    
var regex = new RegExp('(' + words.join('|') + ')', "ig");

document.body.innerHTML = product.replace(regex, "<b>$1</b>");

【讨论】:

  • 感谢您的帮助,这个答案也可以解决我的问题,但我用@OriDrori 答案解决了这个问题,+1。
猜你喜欢
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-09
相关资源
最近更新 更多