简体   繁体   English

将可变字括起来

[英]Wrap variable words in a span

Based on a variety of user inputs, we put an array of words in a hidden div (#words) and then perform functions using that info. 根据各种用户输入,我们将一个单词数组放在一个隐藏的div(#words)中,然后使用该信息执行功能。

What I would like to do is check the div for the existing words, ie: 我想做的是检查div中是否存在现有单词,即:

terms = $("#words").html();

And then, in a visible and separate div elsewhere on the page (.ocrText), wrap only those words in a strong tag. 然后,在页面上其他地方的可见且独立的div(.ocrText)中,仅将这些单词包装在一个强标签中。

$('.ocrText').each(function() {
  $(this).html($(this).html().replace(/term/g, "<strong>term</strong>"));
});

So, if they'd searched for "Tallant France" and we stored that, then the following sentence: 因此,如果他们搜索了“ Tallant France”并且我们将其存储起来,那么下面的句子就是:

"Mark Tallant served in France." “马克·塔兰特在法国任职。”

Would become: 会成为:

"Mark <strong> Tallant </strong> served in <strong>France</strong> ." “马克<strong>塔兰特</strong><strong>France</strong>服役。”

But I don't know how to inject that variable in to .replace() 但是我不知道如何将变量注入.replace()

/// ///

EDIT: The terms are inserted in to the #words div in this format: ["Tallant","France","War"] ... and so on. 编辑:术语以以下格式插入到#words div中:[“ Tallant”,“ France”,“ War”] ...等。

$('.ocrText').each(function() {
    var term = 'term'
    var pattern = RegExp(term, 'g')
    $(this).html($(this).html().replace(pattern, "<strong>" + term + "</strong>"));
});

Assuming your words contain only alphnumeric characters you can construct a single regexp to search of all of them at once as follows: 假设您的单词仅包含字母数字字符,则可以构造一个正则表达式来一次搜索所有正则表达式,如下所示:

html = html.replace (
  new RegExp(terms.split(/\s*,\s*|\s+/).join('|'), 'g'), '<strong>$&</strong>');

The split should convert the terms string into an array containing the individual words, in the example I have coded it to split on commas optionally surround by whitespace or just whitespace. 拆分应将术语字符串转换为包含各个单词的数组,在本例中,我已对其进行了编码,以逗号分隔(可选地由空格或仅由空格包围)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM