Is it possible, using Javascript, to highlight (in yellow..) all the
occurrences of "number: [0-9]+" (regex) of the document?
Merx
Yes.
Good.
In a search on the web I found this page
http://www.nsftools.com/misc/SearchAndHighlight.htm that describe how to do
it using normal (not regex) search terms.
They wrote:
// we're not using a
// regular expression search, because we want to filter out
// matches that occur within HTML tags and script blocks, so
// we have to do a little extra validation
What does this mean? that is not directly possible to make a regex search on
rendered text ignoring HTML tags and script blocks?
Merx
Sure, enter "number\s\d" (without the quotes) in the input field, check the
"regex" checkbox, and look at the last line of the example text at
<URL: http://4umi.com/web/javascript/hilite.htm >
Below is the function that is called by the form:
function highlight(t, el) {
if (!t) return;
if(!document.getElementById('regex').checked)
t = t.replace(/([\\|^$()[\]{}.*+?])/g, '\\$1');
if (/^\s*$/.test(t)) return;
var r, p = document.getElementById('case').checked? 'g':'gi';
if (document.getElementById('literal').checked) {
r = new RegExp(t, p);
} else {
r = new RegExp(t.split(/\s+/).join('|'), p);
}
var s = [el||document.documentElement||document.body];
var h = document.createElement('span'), i = 0, e, j, l, o, k;
h.style.backgroundColor = '#ff0';
do {
e = s[i];
if (e.nodeType == 3) {
r.lastIndex = 0;
l = r.exec(e.nodeValue);
if (l != null) {
k = l[0].length;
if (r.lastIndex > k) {
e.splitText(r.lastIndex-k);
e = e.nextSibling;
}
if (e.nodeValue.length > k) {
e.splitText(k);
s[i++] = e.nextSibling;
}
o = h.cloneNode(true);
o.appendChild(document.createTextNode(l[0]));
e.parentNode.replaceChild(o, e);
}
} else {
j = e.childNodes.length;
while (j) s[i++] = e.childNodes.item(--j);
}
} while(i--);
}
HTH
Ivo
Thanks. It works. But it stop to work well when there are html tags between
the words.
How to ignorate html tags and operate on the rendered text only?
Merx
>
> In a search on the web I found this page
> http://www.nsftools.com/misc/SearchAndHighlight.htm that describe how to do
> it using normal (not regex) search terms.
>
> They wrote:
>
> // we're not using a
> // regular expression search, because we want to filter out
> // matches that occur within HTML tags and script blocks, so
> // we have to do a little extra validation
>
> What does this mean? that is not directly possible to make a regex search on
> rendered text ignoring HTML tags and script blocks?
You can isolate textNodes, see W3C dom particulars.
IE uses "element.innerText", but this won't work on many browsers.
Mick
> Merx
>
>