Working with the String Object


Working with the String Object

Working with strings is not difficult, and we'll see several examples here. It's worth noting that you can use "escaped" codes to stand for special characters in a string. Here are a few of those codes, all of which start with a backslash (\):

  • \" Double quote

  • \' Single quote

  • \\ Backslash

  • \b Backspace

  • \t Tab

  • \n New line

  • \r Carriage return

  • \f Form feed

To embed a tab in a string, for instance, you can do something like this: "Here\tThere." (which translates as "Here[TAB]There." ). Let's take a look at a few of the String methods now.

Changing Case

You can change the case of text using the String toUpperCase and toLowerCase methods. Here's an example that enables you to change the case of text just by clicking buttons :

(Listing 18-07.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Changing Case          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function lower()   {   document.form1.text1.value = document.form1.text1.value.toLowerCase()   }   function upper()   {   document.form1.text1.value = document.form1.text1.value.toUpperCase()   }  // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Changing Case</H1>          <FORM NAME="form1">              <INPUT TYPE="TEXT" NAME="text1" VALUE="Text">              <BR>              <INPUT TYPE="BUTTON" ONCLICK="lower()" VALUE="Lower case">              <INPUT TYPE="BUTTON" ONCLICK="upper()" VALUE="Upper case">          </FORM>      </BODY>  </HTML> 

You can see the results of this code in Figure 18.7, where I've capitalized some text by clicking a button.

Figure 18.7. Changing text case.

graphics/18fig07.gif

Formatting Text

The String object contains many methods for formatting text by surrounding that text with HTML tags. Here's an example where I'm using the bold , italics , strike , and big String methods to work on some text and display it (if you're using the Netscape Navigator, you'll need version 6+ here to handle the getElementById function):

(Listing 18-08.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Searching Strings          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--             function formatter()              {  document.getElementById("div1").innerHTML = "Now ".bold() +   "is ".italics() + "the ".strike() + "time.".big()  }              // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Searching Strings</H1>          <FORM NAME="form1">              <DIV ID="div1">Now is the time.</DIV>              <BR>              <INPUT TYPE="BUTTON" ONCLICK="formatter()" VALUE="Format Text">          </FORM>      </BODY>  </HTML> 

You can see the results of this code in Figure 18.8, where I've formatted some text just by clicking a button.

Figure 18.8. Formatting text.

graphics/18fig08.gif

Splitting Strings

You can also split strings into an array of substrings, which is useful, for example, if the user enters a series of commands all in the same text string. To do this, you use the split String method and specify the character(s) (or regular expression) that you want to split the string on. For example, splitting the string "Now is the time" on spaces will create an array of strings whose elements are "Now" , "is" , "the" , and "time" . Here's an example, where I'm doing exactly that and displaying the resulting substrings in a text area:

(Listing 18-09.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Splitting Strings          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function split()   {   var stringArray = document.form1.text1.value.split(" ")   var text = "You typed: \n"   for (var loopIndex = 0; loopIndex < stringArray.length; loopIndex++){   text += stringArray[loopIndex] + "\n"   }   document.form1.textarea1.value = text   }  // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Splitting Strings</H1>          <FORM NAME="form1">              <INPUT TYPE="TEXT" NAME="text1" VALUE="Now is the time">              <BR>              <INPUT TYPE="BUTTON" ONCLICK="split()" VALUE="Split String">              <BR>               <TEXTAREA ROWS="6" NAME="textarea1"></TEXTAREA>          </FORM>      </BODY>  </HTML> 

You can see the results of this code in Figure 18.9, where I've split the text and the code displays the results.

Figure 18.9. Splitting strings.

graphics/18fig09.gif

Searching Strings

You also can search strings using the indexOf and lastIndexOf methods. The indexOf method returns first index of a substring in the main string, and the lastIndexOf method returns last index of a substring in the main string. Here's an example, which searches for the letter t in the text "Now is the time" :

(Listing 18-10.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Searching Strings          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function findT()   {   var firstT = document.form1.text1.value.indexOf("t")   var text = "First 't' found at index " + firstT + "\n"   var lastT = document.form1.text1.value.lastIndexOf("t")   text += "Last 't' found at index " + lastT + "\n"   document.form1.textarea1.value = text   }  // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Searching Strings</H1>          <FORM NAME="form1">              <INPUT TYPE="TEXT" NAME="text1" VALUE="Now is the time">              <BR>              <INPUT TYPE="BUTTON" ONCLICK="findT()" VALUE="Find the letter 't'">              <BR>              <TEXTAREA ROWS="2" COLS = "30" NAME="textarea1"></TEXTAREA>          </FORM>      </BODY>  </HTML> 

You can see the results of this code in Figure 18.10, where the code has found the first and last t in the text.

Figure 18.10. Searching strings.

graphics/18fig10.gif

Searching and Replacing

You can search a string and replace matches with another string using the String object's replace method. In such a case, you have to supply a regular expression (see Chapter 20) that matches the substring(s) you want to replace, and the replacement string.

Here's an example. In this case, we'll search for the text is in the phrase "Now is the time" and replace it with the text isn't . Here's what the code looks like (the g modifier in the regular expression makes the search-and-replace operation global, which makes it match all occurrences of is ):

(Listing 18-11.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Replacing Text          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function replacer()   {   var regExp = /is/g   var text = document.form1.text1.value.replace(regExp, "isn't")   document.form1.text1.value = text   }  // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Replacing Text</H1>          <FORM NAME="form1">              <INPUT TYPE="TEXT" NAME="text1" VALUE="Now is the time">              <BR>              <INPUT TYPE="BUTTON" ONCLICK="replacer()" VALUE="Replace Text">          </FORM>      </BODY>  </HTML> 

You can see the results of this code in Figure 18.11, where the code has changed is to isn't . That's all there is to it.

Figure 18.11. Replacing text.

graphics/18fig11.gif

That completes our look at the Date and String objects in this chapter. As you can see, there's a lot of programming power here. In the next chapter, we'll keep going in the same direction as we take a look at the Math , Number , Boolean , and Array objects.



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net