Home » Jquery » javascript – A higlight/mark function based on the following code-Exceptionshub

javascript – A higlight/mark function based on the following code-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I am trying to make a simple highlight function using Javascript and jQuery, however I have two issues I can get around at the moment.

Firstly the following code switches the matching words with the searched ones (which I don’t want).

Secondly the script targets nodes from the body (tags), which is also an undesired effect.

Based on the script can someone help with the issues at hand. I’ve tried using the match function with not much success. I know there are Plugins for this specific task, but I wish to do it without them.

function search_x() {
  $('#hint_search').css('visibility', 'hidden');
  $('#hint_search').css('color', 'transparent');
  $('#nav_tooltip_2').css('height', '0');
  $('#nav_tooltip_1').css('height', '0');

  var search_word = prompt("Search for text", "");
  var s_reg = new RegExp(search_word, "gim");
  var str_n = $('body').text();
  var spn_str = "<mark>" + search_word + "</mark>";
  //var res = str_n.match(s_reg);

  if (search_word == null || search_word == "") {
    //if empty input clean mark tag
    alert("No input");
    $("body").html($("body").html().replace(/<mark>/gi, ''));
    $("body").html($("body").html().replace(/<\/mark>/gi, ''));
  } else {
    //clean previous searches
    $("body").html($("body").html().replace(/<mark>/gi, ''));
    $("body").html($("body").html().replace(/<\/mark>/gi, ''));
    $("body").html($("body").html().replace(s_reg, spn_str));
  };
}
How to&Answer: