14.08.2016 Views

Beginning JavaScript with DOM Scripting and Ajax, 2nd Edition

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 2 ■ Data <strong>and</strong> Decisions<br />

Let’s do that next, using the prompt()method to obtain the user’s e-mail address <strong>and</strong> then check the input for the<br />

@ symbol, returning the index of the symbol using indexOf():<br />

<br />

<br />

<br />

var userEmail= prompt("Please enter your emailaddress ", "" );<br />

document.write( userEmail.indexOf( "@" ) );<br />

<br />

<br />

<br />

If the @ is not found, –1 is written to the page. As long as the character is there in the string somewhere, its<br />

position in the index—in other words, something greater than –1,will be returned.<br />

The substring() method carves one string from another string, taking the indexes of the start <strong>and</strong> end positions<br />

of the substring as parameters. You can return everything from the first index to the end of the string by leaving off the<br />

second parameter.<br />

So, to extract all the characters from the third character (at index 2) to the sixth character (index 5), you’d write<br />

<br />

<br />

<br />

var myOldString = "Hello World";<br />

var myNewString = myOldString.substring( 2, 5 );<br />

document.write( myNewString );<br />

<br />

<br />

<br />

You should see llo written out to the browser. Note that the substring() method copies the substring that it<br />

returns, <strong>and</strong> it doesn’t alter the original string.<br />

The substring() method really comes into its own when you’re working <strong>with</strong> unknown values. Here’s another<br />

example that uses both the indexOf() <strong>and</strong> substring() methods:<br />

<br />

<br />

<br />

var characterName = "my name is Simpson, Homer";<br />

var firstNameIndex = characterName.indexOf( "Simpson," ) + 9;<br />

var firstName = characterName.substring( firstNameIndex );<br />

document.write( firstName );<br />

<br />

<br />

<br />

You’re extracting Homer from the string in the variable characterName, using indexOf() to find the start of the last<br />

name <strong>and</strong> adding 9 to it to get the index of the start of the first name (because "Simpson, " is 9 characters long), <strong>and</strong><br />

storing it in firstNameIndex. This is used by the substring() method to extract everything from the start of the first<br />

name—you haven’t specified the final index, so the rest of the characters in the string will be returned.<br />

Now let’s look at the Date object. This allows you to store dates <strong>and</strong> provides some useful date/time-related<br />

functionality.<br />

26<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!