0

When i hit Ctrl+F to find words in chrome all the letters with the search text becomes yellow. Anyone have any idea how it is done? Am just curious to know this!

BTW i'am searching for this is to implement a functionality like this using google extensions. Right now what am doing is finding that particular text and replace it with something like below.

Original text: hello
Replaced text: '<span style="background:yellow;">hello</span>';

Any ideas?

locknies
  • 1,345
  • 3
  • 15
  • 36
  • 2
    For search result is reserved tag `MARK` which should automatically have same color as default search results (defined by OS theme). `hello`. But this is usually used by server or JS, not the browser or its extensions. – Radek Pech Jul 29 '16 at 06:54
  • 1
    See also mark.js library. – wOxxOm Jul 29 '16 at 07:55
  • You can find fully explained code in [hilitor.js](http://www.the-art-of-web.com/javascript/search-highlight/) – Iván Nokonoko Jul 29 '16 at 11:00

1 Answers1

0

Edit: I think browsers don't allow you to use native higlight mechanism. But you can imitate this functionality using Javascript/jQuery.

There are lots of javascript and jQuery plugins to do that. General idea is finding all occurrences of the given word(s) and replacing them with some HTML code. (Which have different background color or larger font size etc.) For find-replace operations, RegEx will be beneficial.

Basic, non-optimized example;

/* Instead of body you can use any container element's selector */
$('body').each(function(){
    var allContent = $(this).text();
    var wordsToBeHighlighted = ['Hello','World'];
    wordsToBeHighlighted = $.map(wordsToBeHighlighted, function(str) {
       return preg_quote(str);
    });
    $(this).html(allContent.replace(new RegExp("(" + wordsToBeHighlighted.join('|') + ")" , 'gi'), "<b style='color: red;'>$1</b>"));
});

function preg_quote( str ) {
    return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}

Source

Community
  • 1
  • 1
Tuğca Eker
  • 1,493
  • 13
  • 20
  • I know this and i replace my text like this like i have explained. i would like to know how the native highlight method works. – locknies Jul 29 '16 at 07:05
  • @KRIZTE You should mark this question with `google-chrome-extension` keyword instead of `javascript`. – Radek Pech Jul 29 '16 at 07:19
  • @KRIZTE, the browser does it internally in the renderer and there's no API for that. It was asked previously on stackoverflow. – wOxxOm Jul 29 '16 at 07:57