Learning
Learning

Reputation: 20001

wrap matching words in a link using jquery

I am working on a functionality which will convert matching tags or keywords into links inside particular DIV tag.

Background: I store article body & keywords related to articles in database & while display article in a web page i pass keywords as and array to jQuery function which then search's through the text inside <div id ="article-detail-desc" > ...</div> and converts each matching element into link.

My code works fine but it has flows.

  1. It doen't search for words it search's for any match even if it is part of a word or HTML element which breaks my HTML code.

how can this function be modified so that it also search for matching words

function HighlightKeywords(keywords)
{        
    var el = $("#article-detail-desc");
    var language = "en-US";
    var pid = 100;
    var issueID = 10; 

    $(keywords).each(function()
    {
        var pattern = new RegExp("("+this+")", ["gi"]);
         var rs = "<a class='ad-keyword-selected' href='en/search.aspx?Language="+language+"&PageId="+pid+"&issue="+issueID+"&search=$1' title='Seach website for:  $1'><span style='color:#990044; tex-decoration:none;'>$1</span></a>";
        el.html(el.html().replace(pattern, rs));
    });
}   

HighlightKeywords(["Amazon","Google","Starbucks","UK","US","tax havens","Singapore","Hong Kong","Dubai","New Jersey"]);

Link on fiddle http://jsfiddle.net/Dgysc/25/

Upvotes: 0

Views: 898

Answers (2)

Loamhoof
Loamhoof

Reputation: 8293

I think the easiest way would be to use word boundaries. So you'd have that:

var pattern = new RegExp("(\\b"+this+"\\b)", ["gi"]);

Edit:
Quick hack to be sure it's not matching the US inside the html elements:

var pattern = new RegExp("(\\b"+this+"\\b)(?![^<]*?>)", ["gi"]);

Upvotes: 1

Anjith K P
Anjith K P

Reputation: 2158

SInce we are using direct word matching, adding space before and after the keywords may help you,

var pattern = new RegExp("( "+this+" )", ["gi"]);

http://jsfiddle.net/Dgysc/28/

Upvotes: 1

Related Questions