Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Web
Expertise: Intermediate
Feb 2, 2000

Find Text Programmatically With textRange

Browsers Targeted: Internet Explorer 4+

You can find a string of text within a document programmatically using the textRange object, which handles most of the internal string manipulation capabilities in Internet Explorer. Specifically, the textRange.findText() function will help you locate the string in question. For example, this script will locate the term typed into the input field anywhere within the document, and will then select that range.

 
<script language="JavaScript">
	// Set the range initially to be the entire document
	var range=document.body.createTextRange();
	function findExpression(){
		expr=searchTextBox.value;
		if (expr!=""){
			// Find the rslt -- the range changes automatically.
			rslt=range.findText(expr,1,0)
			if (rslt){
				// Select the found text
				range.select();
				// move the range to the right of the current range
				range.collapse(false);
				}
			else {
				// reset the range to the whole document.
				alert("The expression '"+expr+"' was not found.");
				range=document.body.createTextRange();
				}
			}
		}
</script>
 
<input type="text" id="searchTextBox" value="textRange" />
<input type="button" value="Search" onclick="findExpression()" />

The third parameter of the findText method can be used to restrict the search. Normally, the value of this parameter is 0. If it's set to 2, then the expression will only match whole words. If set to 4, the expression becomes case sensitive (by default, it's not).

Kurt Cagle
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap