Strings and Arrays are viewed as objects in JavaScript

 

JavaScript Strings & Arrays 

In JavaScript strings are stored as objects. Strings can be declared in two ways. The first one is by assigning the value within double quotes and the second one is by using the new keyword.

mystring=“Welcome to JavaScript”;

mystring=new String(“Welcome to JavaScript”);

 

Both the above declarations are valid and there is absolutely no difference between the two.

Calculating the length of the string

The length of a string can be calculated by using the length () method.

var mystring=”JavaScript”

document.write(mystring.length)

The above statement produces a result of nine to be printed. The index of last character of the string is equal to the length of the string minus one

  charAt() method

This method is used to return a character by giving its index value as an argument . The characters of a string are indexed from zero to the length minus one.

var mystring=”JavaScript”

document.write(mystring.charAt(4))

The above statement writes the character ”S” to the current document as it is the fifth character in the string. This method can also be called with a literal :

document.write(“JavaScript”.chartAt(4))

The above version also produces the same result as before.

indexOf() method

This method returns the index Of the first occurrence of the given substring in the calling string object :

var mystring=”JavaScript”

document.write(str.indexOf(“so”))

The above script produces an output of 5 to be printed. The first occurrence of the substring occurs at the sixth character of the substring. Therefore its index value 5 is printed. Another variation of the indexOf  method is to give the occurrence number of the substring.

var mystring = “baddba”

document.write(mystring.indexOf (“ba”,2))

The above script writes the second occurrence of the string “ba” to the current document. The general syntax for the indexOf() method is :

stringName.indexOf (searchvalue,[occurrence Number])

 lastIndexOf()

This method similar to the indexOf() method except that the last occurrence of the specified string is returned.

substring()

The substring method can be used to return a portion of the main string. It takes in two parameters. The systax for substring() method is :

stringName.substring(startIndex, endIndex +1)

The startIndex indicates the index of the first character in the substring and endIndex indicates the last index of the substring.

var mystring=”JavaScript”

var mystring=mystring.substring(3,7)

The above statements assign ascr to the variable newstring.

Split()

The split method is used to separate a string based upon a specified delimiter. The following example illustrates the use of split :

var mystring=”JavaScript learn from the leader”

var mysplit = mystring.split(“ ”)

The above script results in mystring being split based on the delimiter blankspace. The result is stored in an array mysplit.

toLower Case() and toUpper Case()

As the names indicate the toUpperCase() and toLowerCase() methods are used to convert cases in alphabetic characters.

var s = “JavaScript”

document.write(s.toUpperCase())

document.write(s.toLowerCase())

The above script writes JAVASCRIPT and javascript to the current document.

The following is an example to demonstrate the various methods associated with the String object :

Code-

            <html>

            <head>

            <title> STRING OBJECT</title>

            </head>

            <body>

            <h2> <i> This program demonstrates the use of the String object  </i></h2>

            <script language = “JavaScript”>

             <!-

             var str = “You are studying JavaScript at JavaScriptStyle”

            with(document) {

            write(“The length of the string is”)

            write(str.length +”<br>”)

            write(“The character at third position is “+”<br>”)

            write(str.charAt(2) + “<br>”)

            write(“The index of Ja is “+”<br>”)

            write(str.indexOf(“Ja”)+”<br>”)

            write(“The lastindexof as is”+”<br>”)

            write(str.lastIndexOf(“as”)+”<br>”)

            }

             //-

            </script>

            </body>

            </html>

The second example illustrates the use of the substring() , toUpperCase(), toLowerCase() and the split function.

Code

         <html>

        <head>

         <title>STRING OBJECT</title>

         </head>

         <body>

         <h2><i> This program demonstrates the use of the String  object</i></h2>

          <script language=”JavaScript”>

          <!-

          var str = “You are studying JavaScript at JavaScriptStyle”

     with (document){

     write(“The original string is”+”<br>”)

     write(str+”<br>”)

     write(“A substring of the string is”+”<br>”)

     write(str.substring(10,15)+”<br>”)

     write(“The uppercase of the string is”+”<br>”)

     write(str.toUpperCase()+”<br>”)

     write(“The lowercase of the string is”+”<br>”)

     write(str.toLowerCase()+”<br>”)

     write(“The split function”+”<br>”)

     mystr=str.split(“ ”)

     for (i=0 ; i<mystr.lenght;++i)

     write(mystr[i]+”<br>”)

     }

     //->

     </script>

     </body>

     <html>

Arrays

toString()

This method returns a string of the array elements. The array elements in the string are separated by commas.

Join()

Join method is similar to the toString method except that a separator string can be given. If no separator is mentioned, commas separate the array elements. The syntax for join method is :

join(separator)

reverse()

As the name indicates the reverse method is used to reverse the elements in an array.

Sort()

The sort function sorts the elements of an array in the dictionary order. An optional comparison function can be given based upon which the sorting is done. In case the comparison function is given it should take in two parameters. The function should return a negative number  if the first parameter is less than the second, zero if both parameters are equal and a positive number if the first parameter is greater than the second. The following example demonstrates the use of the various methods associated with array object.

Code-

     <html>

     <head>

     <title>ARRAY OBJECT</title>

     </head>

     <body>

     <script language=”JavaScript”>

     <!

      array=[0,1,2,3,4,5,6,7,8,9,10]

      with(document){

      write(“The output of toString method”+”<br>”)

      write(array.toString()+”<br>”)

      write(“The output of join method”+”<br>”)

      write(array.join(“Java”)+”<br>”)

      write(“The output of reverse method+”<br>”)

      write(array.reverse()+”<br>”)

      write(“The output of sort method”+<br>”)

      write(array.sort()+”<br>”

       }

       //->

      </script>

      </body>

      </html>

1 comment

  1. Peter Galiba

    The new String(“”) and “” are totally different from each other. First is an object, the second is a primitive string. Primitives are passed by value, objects are passed by reference for example. If you check the (typeof new String(“”)) it will return “object” while (typeof “”) will return “string”. Also
    o = new String(“”);
    s = “”;
    if (s) {
    //this will never be reached as the string is empty.
    }
    if (o) {
    // this will always be reached, as every object is truthy.
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>