2 * Plugin that highlights matched word partials in a given element
3 * TODO: add a function for restoring the previous text
4 * TODO: accept mappings for converting shortcuts like WP: to Wikipedia:
10 // Split our pattern string at spaces and run our highlight function on the results
11 splitAndHighlight: function( node
, pat
) {
12 var patArray
= pat
.split(" ");
13 for ( var i
= 0; i
< patArray
.length
; i
++ ) {
14 if ( patArray
[i
].length
== 0 ) continue;
15 $.highlightText
.innerHighlight( node
, patArray
[i
] );
19 // scans a node looking for the pattern and wraps a span around each match
20 innerHighlight: function( node
, pat
) {
21 // if this is a text node
22 if ( node
.nodeType
== 3 ) {
23 // TODO - need to be smarter about the character matching here.
24 // non latin characters can make regex think a new word has begun: do not use \b
25 // http://stackoverflow.com/questions/3787072/regex-wordwrap-with-utf8-characters-in-js
26 // look for an occurence of our pattern and store the starting position
27 var pos
= node
.data
.search( new RegExp( "(^|\\s)" + $.escapeRE( pat
), "i" ) );
29 // create the span wrapper for the matched text
30 var spannode
= document
.createElement( 'span' );
31 spannode
.className
= 'highlight';
32 // shave off the characters preceding the matched text
33 var middlebit
= node
.splitText( pos
);
34 // shave off any unmatched text off the end
35 middlebit
.splitText( pat
.length
);
36 // clone for appending to our span
37 var middleclone
= middlebit
.cloneNode( true );
38 // append the matched text node to the span
39 spannode
.appendChild( middleclone
);
40 // replace the matched node, with our span-wrapped clone of the matched node
41 middlebit
.parentNode
.replaceChild( spannode
, middlebit
);
43 // if this is an element with childnodes, and not a script, style or an element we created
44 } else if ( node
.nodeType
== 1 && node
.childNodes
&& !/(script|style)/i.test( node
.tagName
)
45 && !( node
.tagName
.toLowerCase() == 'span' && node
.className
.match( /\bhighlight/ ) ) ) {
46 for ( var i
= 0; i
< node
.childNodes
.length
; ++i
) {
47 // call the highlight function for each child node
48 $.highlightText
.innerHighlight( node
.childNodes
[i
], pat
);
54 $.fn
.highlightText = function( matchString
) {
55 return $( this ).each( function() {
56 var $this = $( this );
57 $this.data( 'highlightText', { originalText
: $this.text() } );
58 $.highlightText
.splitAndHighlight( this, matchString
);