views:

96

answers:

2

My autocomplete results for each item looks something like this:

<h3>Celebrity Sweepstakes</h3><p>0 episodes</p>

But I want only the title inside the H3 to be highlighted. See the 'highlight' function below. I'm not sure how to change that original RegExp to only replace inside the title.

$(".show_autocomplete").autocomplete("/shows.js", {
        minChars: 2,
        max: 100,
  formatItem:function(item, index, total, query){
    return "<h3>" + item.title + "</h3><p>" + item.episodes + " episodes</p>"
  },
  formatMatch:function(item){
    return item.title;
  },
  formatResult:function(item){
    return item.title;
  },
  dataType:'json',
  parse:function(data) {
    return $.map(data, function(item) {
      return {
        data: item,
        value: item.title,
        result: item.title
      }
    });
  },
  highlight: function(value, term) {
    var title = value.split("</h3>")[0].replace("<h3>", ""); //only replace inside this?
    return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"); //original regexp
  }
}); 
A: 

This might best be solved by breaking it down a bit further. Aside from the fact that it is not being applied only to the <h3>-content, is the current implementation otherwise working as desired?

If so, then instead of making the regex more complicated, you could separate the functionality out just a bit. Add code to identify and extract the title/<h3>-content, and then perform the highlighting on that with the code you have currently. Then take the results and combine them back with the rest of the original input and voila, <h3>-only highlighting.

A secondary benefit is that this approach is likely to make your intentions significantly more clear than a complicated regex, aiding in future maintenance, should other adjustments be needed.

JGB146
A: 

Why make it harder than it is right? :) This is what I got from your idea and works great:

  formatItem:function(item, index, total, query){
    return "<h3><a href=\"/show/" + item.permalink + "\">" + item.title + "</a></h3><p>" + item.followers + " followers | " + item.episodes + " episodes</p>"
  },

  highlight: function(value, term) {
    var value = $(value);
    value.find("a").html(value.find("a").html().replace(RegExp(term, "gi"), "<strong>" + term + "</strong>"));
    return value;
  }
Frexuz