Export (0) Print
Expand All

Finding Text in the Document

Note  As of December 2011, this topic has been archived and is no longer actively maintained. For more information, see Archived Content. For information, recommendations, and guidance regarding the current version of Windows Internet Explorer, see Internet Explorer Developer Center.

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.

Examples

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");

Click to view 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";
}

Click to view sample.

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 Microsoft 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();
}

Click to view sample.

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.

 

 

Show:
© 2014 Microsoft