Javascript: highlight substring keeping original case but searching in case insensitive mode

25,358

Solution 1

Use a function for the second argument for .replace() that returns the actual matched string with the concatenated tags.

Try it out: http://jsfiddle.net/4sGLL/

reg = new RegExp(querystr, 'gi');
       // The str parameter references the matched string
       //    --------------------------------------v
final_str = 'foo ' + result.replace(reg, function(str) {return '<b>'+str+'</b>'});
$('#' + id).html(final_str);​

JSFiddle Example with Input: https://jsfiddle.net/pawmbude/

Solution 2

ES6 version

const highlight = (needle, haystack) =>
  haystack.replace(
      new RegExp(needle, 'gi'),
      (str) => `<strong>${str}</strong>`
  );

Solution 3

While the other answers so far seem simple, they can't be really used in many real world cases as they don't handle proper text HTML escaping and RegExp escaping. If you want to highlight every possible snippet, while escaping the text properly, a function like that would return all elements you should add to your suggestions box:

function highlightLabel(label, term) {
  if (!term) return [ document.createTextNode(label) ]
  const regex = new RegExp(term.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'), 'gi')
  const result = []
  let left, match, right = label
  while (match = right.match(regex)) {
    const m = match[0], hl = document.createElement('b'), i = match.index
    hl.innerText = m
    left = right.slice(0, i)
    right = right.slice(i + m.length)
    result.push(document.createTextNode(left), hl)
    if (!right.length) return result
  }
  result.push(document.createTextNode(right))
  return result
}

Solution 4

nice results with

function str_highlight_text(string, str_to_highlight){
   var reg = new RegExp(str_to_highlight, 'gi');
   return string.replace(reg, function(str) {return '<span style="background-color:#ffbf00;color:#fff;"><b>'+str+'</b></span>'});
}

and easier to remember... thx to user113716: https://stackoverflow.com/a/3294644/2065594

Share:
25,358
Giovanni Di Milia
Author by

Giovanni Di Milia

Updated on January 31, 2022

Comments

  • Giovanni Di Milia
    Giovanni Di Milia over 2 years

    I'm trying to write a "suggestion search box" and I cannot find a solution that allows to highlight a substring with javascript keeping the original case.

    For example if I search for "ca" I search server side in a case insensitive mode and I have the following results:

    Calculator

    calendar

    ESCAPE

    I would like to view the search string in all the previous words, so the result should be:

    Calculator

    calendar

    ESCAPE

    I tried with the following code:

    var reg = new RegExp(querystr, 'gi');
    var final_str = 'foo ' + result.replace(reg, '<b>'+querystr+'</b>');
    $('#'+id).html(final_str);
    

    But obviously in this way I loose the original case!

    Is there a way to solve this problem?