Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - JavaScript: Objects

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

String Object - JavaScript(Js)

In this section, we introduce JavaScript’s string- and character-processing capabilities. The techniques discussed here are appropriate for processing names, addresses, telephone numbers, and similar items.

String Object

 

In this section, we introduce JavaScript’s string- and character-processing capabilities. The techniques discussed here are appropriate for processing names, addresses, telephone numbers, and similar items.

 

1. Fundamentals of Characters and Strings

 

Characters are the fundamental building blocks of JavaScript programs. Every program is composed of a sequence of characters grouped together meaningfully that is interpreted by the computer as a series of instructions used to accomplish a task.

 

A string is a series of characters treated as a single unit. A string may include letters, digits and various special characters, such as +, -, *, /, and $. JavaScript supports the set of characters called Unicode®, which represents a large portion of the world’s languages.

 

(We discuss Unicode in detail in Appendix F.) A string is an object of type String. String literals or string constants (often called anonymous String objects) are written as a sequence of characters in double quotation marks or single quotation marks, as follows:

"John Q. Doe"    (a name)

'9999 Main Street'    (a street address)

"Waltham, Massachusetts"   (a city and state)

'(201) 555-1212'     (a telephone number)

A String may be assigned to a variable in a declaration. The declaration

 

var color = "blue";

 

initializes variable color with the String object containing the string "blue". Strings can be compared via the relational (<, <=, > and >=) and equality operators (== and !=). Strings are compared using the Unicode values of the corresponding characters. For example, the expression "hello" < "Hello" evaluates to false because lowercase letters have higher Uni-code values.

 

2. Methods of the String Object

 

The String object encapsulates the attributes and behaviors of a string of characters. It provides many methods (behaviors) that accomplish useful tasks such as selecting charac-ters from a string, combining strings (called concatenation), obtaining substrings of a string, searching for substrings within a string, tokenizing strings (i.e., splitting strings into individual words) and converting strings to all uppercase or lowercase letters. The String object also provides several methods that generate XHTML tags. Figure 11.3 summarizes many String methods. Figures 11.4–11.7 demonstrate some of these methods.





3. Character-Processing Methods

 

The script in Fig. 11.4 demonstrates some of the String object’s character-processing methods, including charAt (returns the character at a specific position), charCodeAt (re-turns the Unicode value of the character at a specific position), fromCharCode (returns a string created from a series of Unicode values), toLowerCase (returns the lowercase version of a string) and toUpperCase (returns the uppercase version of a string).

        <?xml version = "1.0" encoding = "utf-8"?>

 

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

        <!-- Fig. 11.4: CharacterProcessing.html -->

 

        <!-- String methods charAt, charCodeAt, fromCharCode, toLowercase and

 

toUpperCase. -->

    <html xmlns = "http://www.w3.org/1999/xhtml">

 

    <head>

 

      <title>Character Processing Methods</title>

 

      <script type = "text/javascript">

      <!--

 

      var s = "ZEBRA";

 

      var s2 = "AbCdEfG";

document.writeln( "<p>Character at index 0 in '" + s + "' is " + s.charAt( 0 ) );

 

document.writeln( "<br />Character code at index 0 in '"

+ s + "' is " + s.charCodeAt( 0 )    + "</p>" );

                          

document.writeln( "<p>'" +     

     String.fromCharCode( 87, 79, 82, 68  )    +

"' contains character codes 87, 79,  82 and 68</p>" )

                          

document.writeln( "<p>'" + s2 + "' in lowercase is '" +

      s2.toLowerCase() + "'" );

 

      document.writeln( "<br />'" + s2 + "' in uppercase is '"

      + s2.toUpperCase() + "'</p>" );

      // -->

 

      </script>

 

      </head><body></body>

 

</html>


Lines 16–17 display the first character in String s ("ZEBRA") using String method charAt. Method charAt returns a string containing the character at the specified index (0 in this example). Indices for the characters in a string start at 0 (the first character) and go up to (but do not include) the string’s length (i.e., if the string contains five characters, the indices are 0 through 4). If the index is outside the bounds of the string, the method returns an empty string.

 

Lines 18–19 display the character code for the first character in String s ("ZEBRA") by calling String method charCodeAt. Method charCodeAt returns the Unicode value of the character at the specified index (0 in this example). If the index is outside the bounds of the string, the method returns NaN.

 

String method fromCharCode receives as its argument a comma-separated list of Unicode values and builds a string containing the character representation of those Uni-code values. Lines 21–23 display the string "WORD", which consists of the character codes 87, 79, 82 and 68. Note that the String object calls method fromCharCode, rather than a specific String variable. Appendix D, ASCII Character Set, contains the character codes for the ASCII character set—a subset of the Unicode character set (Appendix F) that con-tains only Western characters.

 

The statements in lines 25–26 and 27–28 use String methods toLowerCase and toUpperCase to display versions of String s2 ("AbCdEfG") in all lowercase letters and all uppercase letters, respectively.

 

4. Searching Methods

 

Being able to search for a character or a sequence of characters in a string is often useful. For example, if you are creating your own word processor, you may want to provide a ca-pability for searching through the document. The script in Fig. 11.5 demonstrates the String object methods indexOf and lastIndexOf that search for a specified substring in a string. All the searches in this example are performed on the global string letters (initialized in line 14 with "abcdefghijklmnopqrstuvwxyzabcdefghijklm" in the script).

 

The user types a substring in the XHTML form searchForm’s inputVal text field and presses the Search button to search for the substring in letters. Clicking the Search button calls function buttonPressed (defined in lines 16–29) to respond to the onclick event and perform the searches. The results of each search are displayed in the appropriate text field of searchForm.

 

Lines 21–22 use String method indexOf to determine the location of the first occur-rence in string letters of the string inputVal.value (i.e., the string the user typed in the

 

    <?xml version = "1.0" encoding = "utf-8"?>

 

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

    <!-- Fig. 11.5: SearchingStrings.html -->

 

    <!-- String searching with indexOf and lastIndexOf. -->

 

    <html xmlns = "http://www.w3.org/1999/xhtml">

 

    <head>

 

    <title>

 

      Searching Strings with indexOf and lastIndexOf

 

      </title>

 

      <script type = "text/javascript">

      <!--

 

      var letters = "abcdefghijklmnopqrstuvwxyzabcdefghijklm";

 

      function buttonPressed()

      {

      var        searchForm         = document.getElementById( "searchForm" );

      var        inputVal =   document.getElementById( "inputVal" );

      searchForm.elements[2].value =

                    letters.indexOf( inputVal.value );

      searchForm.elements[3].value =

                    letters.lastIndexOf( inputVal.value );

      searchForm.elements[4].value =

                    letters.indexOf( inputVal.value, 12 );

      searchForm.elements[5].value =

                    letters.lastIndexOf( inputVal.value, 12 );

        } // end function buttonPressed

        // -->

 

        </script>

 

        </head>

 

        <body>

 

        <form id = "searchForm" action = "">

 

        <h1>The string to search is:<br />

        abcdefghijklmnopqrstuvwxyzabcdefghijklm</h1>

 

        <p>Enter substring to search for

 

        <input id = "inputVal" type = "text" />

 

      <input id = "search" type = "button" value = "Search" onclick = "buttonPressed()"   /><br /></p>

 

        <p>First occurrence located at index

 

        <input id = "first" type = "text" size = "5" />

 

        <br />Last occurrence located at index

 

        <input id = "last" type = "text" size = "5" />

 

        <br />First occurrence from index 12 located at index

 

        <input id = "first12" type = "text" size = "5" />

 

        <br />Last occurrence from index 12 located at index

 

        <input id = "last12" type = "text" size = "5" /></p>

 

        </form>

 

        </body>

 

      </html>




Fig. 11.5 | String searching with indexOf and lastIndexOf.

inputVal text field). If the substring is found, the index at which the first occurrence of the substring begins is returned; otherwise, –1 is returned.

 

Lines 23–24 use String method lastIndexOf to determine the location of the last occurrence in letters of the string in inputVal. If the substring is found, the index at which the last occurrence of the substring begins is returned; otherwise, –1 is returned.

 

Lines 25–26 use String method indexOf to determine the location of the first occur-rence in string letters of the string in the inputVal text field, starting from index 12 in letters. If the substring is found, the index at which the first occurrence of the substring (starting from index 12) begins is returned; otherwise, –1 is returned.

Lines 27–28 use String method lastIndexOf to determine the location of the last occurrence in letters of the string in the inputVal text field, starting from index 12 in letters and moving toward the beginning of the input. If the substring is found, the index at which the first occurrence of the substring (if one appears before index 12) begins is returned; otherwise, –1 is returned.

5. Splitting Strings and Obtaining Substrings

 

When you read a sentence, your mind breaks it into individual words, or tokens, each of which conveys meaning to you. The process of breaking a string into tokens is called to-kenization. Interpreters also perform tokenization. They break up statements into such in-dividual pieces as keywords, identifiers, operators and other elements of a programming language. Figure 11.6 demonstrates String method split, which breaks a string into its component tokens. Tokens are separated from one another by delimiters, typically white space characters such as blanks, tabs, newlines and carriage returns. Other characters may also be used as delimiters to separate tokens. The XHTML document displays a form con-taining a text field where the user types a sentence to tokenize. The results of the tokeni-zation process are displayed in an XHTML textarea GUI component. The script also demonstrates String method substring, which returns a portion of a string.

 

The user types a sentence into the text field with id inputVal text field and presses the Split button to tokenize the string. Function splitButtonPressed (lines 12–21) han-dles the button’s onclick event.

 

 

    <?xml version = "1.0" encoding = "utf-8"?>

 

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

    <!-- Fig. 11.6: SplitAndSubString.html -->

 

    <!-- String object methods split and substring. -->

 

    <html xmlns = "http://www.w3.org/1999/xhtml">

 

    <head>

 

    <title>String Methods split and substring</title>

 

      <script type = "text/javascript">

      <!--

 

      function splitButtonPressed()

{

var inputString = document.getElementById( "inputVal" ).value;

var tokens =        inputString.split( " " );  

document.getElementById( "output" ).value =

          tokens.join( "\n" )          ;

                                     

document.getElementById( "outputSubstring" ).value =

          inputString.substring( 0, 10 );

      } // end function splitButtonPressed

      // -->

 

      </script>

 

      </head>

 

      <body>

 

      <form action = "">

 

      <p>Enter a sentence to split into words<br />

 

      <input id = "inputVal" type = "text" size = "40" />

 

<input type = "button" value = "Split"

onclick = "splitButtonPressed()" /></p>

      <p>The sentence split into words is<br />

 

      <textarea id = "output" rows = "8" cols = "34">

 

      </textarea></p>

      <p>The first 10 characters of the input string are

 

      <input id = "outputSubstring" type = "text"

                     size = "15" /></p>

 

      </form>

 

      </body>

 

      </html>


Fig. 11.6 | String object methods split and substring.

Line 14 gets the value of the input field and stores it in variable inputString. Line 15 calls String method split to tokenize inputString. The argument to method split is the delimiter string—the string that determines the end of each token in the original string. In this example, the space character delimits the tokens. The delimiter string can contain multiple characters that should be used as delimiters. Method split returns an array of strings containing the tokens. Line 17 uses Array method join to combine the tokens in array tokens and separate each token with a newline character (\n). The resulting string is assigned to the value property of the XHTML form’s output GUI com-ponent (an XHTML textarea).

 

Lines 19–20 use String method substring to obtain a string containing the first 10 characters of the string the user entered (still stored in inputString). The method returns the substring from the starting index (0 in this example) up to but not including the ending index (10 in this example). If the ending index is greater than the length of the string, the substring returned includes the characters from the starting index to the end of the original string.

 

6. XHTML Markup Methods

 

The script in Fig. 11.7 demonstrates the String object’s methods that generate XHTML markup tags. When a String object invokes a markup method, the method wraps the String’s contents in the appropriate XHTML tag. These methods are particularly useful for generating XHTML dynamically during script processing.

Lines 12–17 define the strings that call each of the XHTML markup methods of the String object. Line 19 uses String method anchor to format the string in variable

anchorText ("This is an anchor") as

 

<a name = "top">This is an anchor</a>

      <?xml version = "1.0" encoding = "utf-8"?>

 

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

      <!-- Fig. 11.7: MarkupMethods.html -->

 

      <!-- String object XHTML markup methods. -->

 

      <html xmlns = "http://www.w3.org/1999/xhtml">

 

      <head>

 

      <title>XHTML Markup Methods of the String Object</title>

 

        <script type = "text/javascript">

        <!--

 

        var anchorText = "This is an anchor";

 

        var fixedText = "This is monospaced text";

 

        var linkText = "Click here to go to anchorText";

 

        var strikeText = "This is strike out text";

 

        var subText = "subscript";

 

        var supText = "superscript";

         

        document.writeln( anchorText.anchor( "top" ) );

 

        document.writeln( "<br />" + fixedText.fixed() );

 

        document.writeln( "<br />" + strikeText.strike() );

 

        document.writeln(

        "<br />This is text with a " + subText.sub() );

 

        document.writeln(

        "<br />This is text with a " + supText.sup() );

 

        document.writeln( "<br />" + linkText.link( "#top" ) );

        // -->

 

        </script>

 

        </head><body></body>

 

</html>



Fig. 11.7 | String object XHTML markup methods.

The name of the anchor is the argument to the method. This anchor will be used later in the example as the target of a hyperlink.

 

Line 20 uses String method fixed to display text in a fixed-width font by formatting the string in variable fixedText ("This is monospaced text") as

 

<tt>This is monospaced text</tt>

 

Line 21 uses String method strike to display text with a line through it by formatting the string in variable strikeText ("This is strike out text") as

 

<strike>This is strike out text</strike>

 

Lines 22–23 use String method sub to display subscript text by formatting the string in variable subText ("subscript") as

 

<sub>subscript</sub>

 

Note that the resulting line in the XHTML document displays the word subscript small-er than the rest of the line and slightly below the line.

 

Lines 24–25 call String method sup to display superscript text by formatting the string in variable supText ("superscript") as

 

<sup>superscript</sup>

 

Note that the resulting line in the XHTML document displays the word superscript smaller than the rest of the line and slightly above the line.

 

Line 26 uses String method link to create a hyperlink by formatting the string in variable linkText ("Click here to go to anchorText") as

 

<a href = "#top">Click here to go to anchorText</a>

 

The target of the hyperlink (#top in this example) is the argument to the method and can be any URL. In this example, the hyperlink target is the anchor created in line 19. If you make your browser window short and scroll to the bottom of the web page, then click this link, the browser will reposition to the top of the web page.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.