0

I want to make matched text in string bold in autocomplete I got great help from this link.

This doesnt it for single word or word which are in sequence I want to make words bold no matter in which order they are.

I want to make each and every word matching in the string bold

var t = "Cadbury Gems 100gm Tasty";
var wordArr = 'gems tasty'.toLowerCase().replace(/\b[a-z]/g, function (letter) {
    return letter.toUpperCase();
}).split(' ');
$.each(wordArr, function (i) {
    console.log(wordArr[i]);
    var re = new RegExp("^" + wordArr[i], "i");
    t = t.replace(re, "<span style='font-weight:bold;color:Blue;'>" + wordArr[i] + "</span>");

})
console.log(t);
var li = $("<li></li>")
//.data("item.autocomplete", item)
.append("<a style='text-align:left'>" + t + "</a>")
    .appendTo($('#ul'));

MY Fiddle

I tried with $.each But doesnt work. Any ideas.

Community
  • 1
  • 1
Nitin Varpe
  • 10,450
  • 6
  • 36
  • 60

2 Answers2

0

Try this one build with jQuery UI widget factory:

$.widget("custom.autocompleteHighlight", $.ui.autocomplete, {
            _renderItem: function (ul, item) {
                var regexp = new RegExp('(' + this.term + ')', 'gi'),
                    classString = this.options.highlightClass ?  ' class="' + this.options.highlightClass + '"' : '',
                    label = item.label.replace(regexp, '<span' + classString + '>$1</span>');

                return $('<li><a href="#">' + label + '</a></li>').appendTo(ul);
            }
    }
});

You now can use it with:

$('input.jsAutocompleteHighlight').autocompleteHighlight({
        highlightClass: 'ui-autocomplete-hightlight'
});

CSS styling:

.ui-autocomplete-highlight {
    font-weight: bold;
}
Henry Ruhs
  • 1,533
  • 1
  • 20
  • 32
0

Use this:

mynew = item.label
$.each(this.term.split(' '),function(k,v){
    var re = new RegExp(v,'i')
    mynew = mynew.replace(re,'<span style="color:red">' + v + '</span>');
})
Pang
  • 9,564
  • 146
  • 81
  • 122
Mem Maina
  • 19
  • 3