I
have modified fastLiveFilter jQuery plugin by adding a
highlight functionality.
I
added a button to the form:
<form id="search_box">
<input type="text"
id="search_input" name="search_box" />
<input id="search-button"
type="button" value="Search"
role="button" />
</form>
The search/filter is not trigger on keyup, but on
pressing the button or the [ENTER] key.
The
function bellow wrapps the searched string in a
span:
function highlightTerm(){
var searchTerm = $(input).val();
$(lis).each(function(){
var liText = $(this).html();
var regex = new RegExp(searchTerm,
'gi');
var found;
var inc = 0;
while((found = regex.exec(liText)) !== null)
{
if (inc += 1 > 100) {
throw 'An infinite loop will
occur.';
}
var word = found[0];
var lastChar = found.index;
var left = liText.substring(0,
lastChar);
var right = liText.substring(lastChar +
word.length);
var insert = '<span
class="highlight">' + word +
'</span>';
// regex.lastIndex =
regex.lastIndex
liText = left + insert +
right;
regex.lastIndex = (regex.lastIndex - word.length)
+ insert.length;
}
$(this).html(liText);
});
}
The
search is case INSENSITIVE.
The
problem is that the searched string is wrapped in the span with
the class "highlight" even if found in URL on the
page. So the function above ruins the links. How do I avoid
this?
To
be more clear: I want to match a word stored in a variable
searchTerm. If searchTerm is "test", it should me
match (and wrapped with a span) in "This it a test"
but not in <a
href="my-test.html">word</a>.
Thank
you!