highlight html strings without breaking tags

This commit is contained in:
j 2012-01-31 12:00:34 +00:00
parent fd96423266
commit 9568acd592
2 changed files with 28 additions and 2 deletions

View file

@ -177,7 +177,7 @@ Ox.Editable = function(options, self) {
value = self.options.format(self.options.value)
}
if (self.options.highlight) {
value = Ox.highlight(value, self.options.highlight, 'OxHighlight');
value = Ox.highlightHTML(value, self.options.highlight, 'OxHighlight');
}
return value;
}

View file

@ -62,6 +62,32 @@ Ox.highlight = function(txt, str, classname) {
) : txt;
};
/*@
Ox.highlightHTML <f> Highlight matches in a html string
> Ox.highlight('<a href="foobar">foobar</a>', 'foo', 'match')
'<a href="foobar"><span class="match">foo</span>bar</a>'
@*/
Ox.highlightHTML = function(txt, str, classname) {
var i = -1,
result = '',
value = txt.toLowerCase();
str = str.toLowerCase();
while (txt.length) {
if ((i = value.indexOf(str, i + 1)) < 0) {
result += txt;
txt = '';
} else if (value.lastIndexOf('>', i) >= value.lastIndexOf('<', i)) {
result += txt.substring(0, i)
+ '<span class="' + classname + '">'
+ txt.substr(i, str.length) + '</span>';
txt = txt.substr(i + str.length);
value = txt.toLowerCase();
i = -1;
}
}
return result;
};
/*@
Ox.isValidEmail <f> Tests if a string is a valid e-mail address
(str) -> <b> True if the string is a valid e-mail address