PDA

View Full Version : findText function


bench
02-05-2003, 01:50 PM
I am trying to allow somebody to search a webpage for certain words. I have succeeded in searching the document for a specific word in the text range, but am having trouble search for the word again if it appears later throughout the document. Here's the code below:

<html>
<head>
<title>New Page 1</title>
<script>
function performSearch(){
var textRange = document.body.createTextRange();
if (textRange.findText("ben")){
textRange.select();
if (textRange.findText("ben")){
textRange.select();
}
}
}
</script>
</head>
<body>
<p><input type="button" value="Button" name="B3" onclick="performSearch();"></p>
<p>dfgdfgdfgbendxfgfgdbenfsdfdben</p>
</body>
</html>

The above code only highlights the first "ben" found in the document, but I would like it to highlight the second "ben" in the document.

Any help with this matter would be most appreciated.

Many Thanks in advanced,
Ben Chivers

piglet
02-17-2003, 08:19 PM
I didn't suggest this!

<html>
<head>
<title>New Page 1</title>
<STYLE TYPE="text/css" TITLE="">
.foo {background-color: pink;}
</STYLE>
<script>
function performSearch(what){
r = new RegExp(what,"gi");
document.body.innerHTML = document.body.innerHTML.replace(r,"<span class='foo'>"+what+"</span>");
}
</script>
</head>
<body>
<p><form>
<input type="button" value="Button" name="B3" onclick="performSearch('ben');">
</form></p>
<p>dfgdfgdfgbendxfgfgdbenfsdfdben</p>
</body>
</html>

beetle
02-17-2003, 08:32 PM
I'd prefer to let the regexp handle the entire replace

r = new RegExp( "("+what+")" ,"gi");
document.body.innerHTML = document.body.innerHTML.replace(r,"<span class='foo'>$1</span>");

This way the case-sesitivity of the replacements is preserved.

Roelf
02-17-2003, 08:53 PM
http://www.codingforums.com/showthread.php?s=&threadid=6036 is this something you want to check out??