You can search for a given string of text in a document by using the findText method on a TextRange object. This method starts the search at the beginning of the range and, if it finds the string, positions the range so that it entirely encloses the string. The following example uses findText to search for each instance of the word "sample" and displays a message identifying how many instances it found.
var rng = document.body.createTextRange(); for (i=0; rng.findText("sample")!=false; i++) { rng.collapse(); } alert("There are " + i + " instances of sample");
In the above example, the collapse method moves the start of the text range to the same position as the end point, ensuring that the same instance of "sample" is not counted twice.
You can carry out a global search and replace by using findText and the text property. The following example searches for each instance of "sample" and replaces it with the word "final".
var rng = document.body.createTextRange(); for (i=0; rng.findText("sample")!=false; i++) { rng.text = "final"; }
You can select the text that you find, making it easier for the user to see, by using the select method. Similarly, you can scroll the text into the user's view by using the scrollIntoView method. Together, these methods give you a way to make the result of a search clearly visible to the user. The following JScript (compatible with ECMA 262 language specification) example searches for the word "sample", selects the word, and then scrolls the word to the top of the window.
var rng = document.body.createTextRange(); if (rng.findText("sample")==true) { rng.select(); rng.scrollIntoView(); }
Note that you can also create a text range from a selection made by the user. The createRange method on the selection object returns a text range. You can use the same methods and properties on this range as you do for ranges created using createTextRange.