简体   繁体   中英

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.

What I would like to do is check the div for the existing words, ie:

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

And then, in a visible and separate div elsewhere on the page (.ocrText), wrap only those words in a strong tag.

$('.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:

"Mark Tallant served in France."

Would become:

"Mark <strong> Tallant </strong> served in <strong>France</strong> ."

But I don't know how to inject that variable in to .replace()

///

EDIT: The terms are inserted in to the #words div in this format: ["Tallant","France","War"] ... and so on.

$('.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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