Note: This demo has been tested working in IE 6, and is known not to work in Firefox 1.5. Support for other browsers depends on whether they support createTextRange or not.
To search and select specific text, you need to create a text range. This can be done using the "createTextRange" method. Once done, you have many methods at your disposal, including "findText" and "select" which let you find and select text, as well as "moveStart" and "moveEnd" which let you control the textrange.
These methods are well documented on MSDN:
http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/objects/obj_textrange.asp
http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/methods/createtextrange.asp
http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/methods/findtext.asp
http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/methods/select_1.asp
http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/methods/movestart.asp
Here's a simple demo showing how to do it with a button press. I've added code to show how to "reset" the selection, too, once the end has been reached:
Code:
<html>
<head>
<script type="text/javascript">
var theRange = null;
window.onload = function() {
try {
theRange = document.getElementById('myText').createTextRange();
} catch(e) {}
if (theRange == null) {
alert('There was an error creating a textRange. Perhaps your browser doesn\'t support them.');
}
}
function findNext() {
if (theRange != null) {
theRange.findText('[ ]');
theRange.select();
var charsMoved = theRange.moveStart('character', 3);
if (charsMoved == 0) {
var startAgain = window.confirm('No more matches found. Start again from the beginning?');
if (startAgain) {
theRange.moveStart('textedit', -1);
findNext();
}
}
}
}
</script>
</head>
<body>
<form>
<textarea id="myText" cols="40" rows="5">Here is some text [ ], and here is some more [ ], and yet even more text! [ ]</textarea>
<br />
<input type="button" onclick="findNext();" value="Find next" />
</form>
</body>
</html>
Dan