spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / java_core / 2 To page 1To page 2current pageTo page 4To page 5To page 6
[previous] [next]

Finance Developer (IL)
Next Step Systems
US-IL-Chicago

Justtechjobs.com Post A Job | Post A Resume
Developer News
OpenOffice 3.2 Lands Amid Critical Changes
Red Hat, IBM Firmly in KVM Virtualization Camp
Red Hat Talks Up Open Source Cloud Plans


JavaScript by Example: JavaScript Core Objects. Pt. 2

Methods That Find a Position in a String

A substring is a piece of an already existing string; thus eat is a substring of both create and upbeat, and java is a substring of javascript. When a user enters information, you want to see if a certain pattern of characters exist, such as the @ in an e-mail address or a zip code in an address. JavaScript provides a number of methods to assist you in finding substrings.


The indexOf() and the lastIndexOf() methods are used to find the first instance or the last instance of a substring within a larger string. They are both case sensitive. The first character in a string is at index value 0, just like array indices. If either of the methods finds the substring, it returns the position of the first letter in the substring. If either method can't find the pattern in the string, then a -1 is returned.

 

<html><head><title>Substrings</title>

</head>

<body bgcolor=lightgreen>

<font face="arial" size="+1">

Searching for an @ sign

<script language="JavaScript">

1 var email_addr=prompt("What is your email address? ","");

2 while(email_addr.indexOf("@") == -1 ){

3 alert( "Invalid email address.");

email_addr=prompt("What is your email address? ",""); }

document.write("<br>OK.<br>");

</script>

</body></html>

 

 
The user is prompted for his e-mail address and the input is assigned to a string called email_addr.

  1. The loop expression uses the indexOf() String method to see if there is an @ symbol in the e-mail address. If there isn't, the indexOf() method returns -1 and the body of the loop is executed.

  2. If the indexOf() method didn't find the @ substring, the alert box appears and the user is prompted again (see Figures 9.24 and 9.25). The loop terminates when the user enters an e-mail address containing an @ sign. Of course, this is just a simple test for validating an e-mail address; more elaborate methods of validation are discussed in Chapter 13, "Regular Expressions and Pattern Matching."

 

Using the indexOf() String method.

The user entered an e-mail address without the @ symbol.

 

<html>

<head><title>String Manipulation</title></head>

</head>

<body>

<h2>Working with String Manipulation Methods</h2>

<script language="JavaScript">

function break_tag(){

document.write("<br>");

}

document.write("<h3>");

1 var str1 = new String("The merry, merry month of June...");

document.write("In the string:<em> "+ str1 );

2 document.write("</em> the first 'm' is at position " +

str1.indexOf("m"));

break_tag();

3 document.write("The last 'm' is at position " +

str1.lastIndexOf("m"));

break_tag();

4 document.write("<em>str1.substr(4,5)</em> returns<em> " +

str1.substr(4,5));

break_tag();

document.write(str1.toUpperCase());

document.write("</h3>");

</script>

</body>

</html>

 

 
Methods that Extract Substrings from a String

You may have to do more than just find a substring within a string, you may need to extract that substring. For example, we found the @ in the e-mail address, now we may want to get just the user name or the server name or domain name. To do this, JavaScript provides methods such as splice(), split(), charAt(), substr(), and substring().

 
 

 

<html><head><title>Extracting Substrings</title>

</head>

<body bgcolor=lightgreen>

<font face="arial" size="+1">

Extracting substrings

<font size="-1">

<script language="JavaScript">

1 var straddr = "DanielSavage@dadserver.org";

document.write("<br>His name is<em> " +
2 straddr.substr(0,6) + "</em>.<br>");

3 var namesarr = straddr.split("@" );

4 document.write( "The user name is<em> " + namesarr[0] +

"</em>.<br>");

5 document.write( "and the mail server is<em> " + namesarr[1] +

"</em>.<br>");

6 document.write( "The first character in the string is <em>" +

straddr.charAt(0)+ "</em>.<br>");

7 document.write( "and the last character in the string is <em>"

+ straddr.charAt(straddr.length - 1)

+ "</em>.<br>");

</script>

</body></html>

 

 
A string is assigned an e-mail address.

  1. The substr() starts at the first character at position 0, and yanks 6 characters from the starting position. The substring is Daniel.

  2. The split() method creates an array, called namesarr, by splitting up a string into substrings based on some delimiter that marks where the string is split. This string is split using the @ sign as its delimiter.

  3. The first element of the array, namesarr[0], that is created by the split() method is DanielSavage, the user name portion of the e-mail address.

  4. The second element of the array, namesarr[1], that is created by the split() method is dadserver.org, the mail server and domain portion of the e-mail address.

  5. The charAt() method returns the character found at a specified position within a string; in this example, position 0. Position 0 is the first character in the string, a letter D.

  6. By giving the charAt() method the length of the string minus 1, the last character in the string is extracted, a letter g. (See Figure 9.27.)

The charAt(), split(), and substr() methods.


home / programming / java_core / 2 To page 1To page 2current pageTo page 4To page 5To page 6
[previous] [next]


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

webref The latest from WebReference.com Browse >
Search Engine Optimization: Selecting and Embedding Keywords · Are Google's Language Translation Web Services Ready for Prime Time? · Installing and Using Meeplace, the Business Review CMS
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
IBM DB2 10 for z/OS: Justifying the Upgrade · Living La Vida Colo: Choosing the Right Colocation Facility · FTC Concerns over Social Media Privacy Linger

Created: March 27, 2003
Revised: November 19, 2003

URL: http://webreference.com/programming/java_core/2