CIS 89C  Client-Side Programming with JavaScript

 

Unit 13 - Timing (week 6)

 

References:

 

McDuffie - Chapter 9 Manipulating Strings

 

 

 

 

***********************************************************

Opening statement

 

We have been using the string primitive element.

Example:

 

"hello"

 

There is also a String wrapper constructor, which allows you to keep a string in an object.

There are several interesting methods for a String object.

 

 

***********************************************************

String() constructor

 

The String constructor takes a primitive string as a parameter,
and makes a wrapper object containing it.

Example:

 

var my_hello_object_reference = new String("hello");

 

The variable my_hello_object is now a reference to an object,
which has the primitive string "hello" as internal data.

 

 

***********************************************************

String() function

 

There is also a String() function.

When you use the String() function without new, it just returns a string.

Example:

 

var phrase = String("hello" + " " + "there");

 

My variable phrase will now contain the primitive string
"hello there"

 

 

***********************************************************

String() properties

 

The String() constructor, provides your new object with only one property:

 

length

 

The length is the number of characters in the primitive string, that is kept internally within the object.

 

 

***********************************************************

Inheritance

 

Do you mean that the String() constructor only provides one property? Yes

Do you mean that there is only property? NO

Make up your mind, what do you mean.

 

Well, what happens is inheritance.

With inheritance, when you ask the String() constructor to build an object,

the String() constructor asks the Object() constructor to provide additional properties and methods.

 

This is called inheritance.

You ask for one constructor, and you also inherit the additional properties and methods provided by the parent of the Constructor you requested.

 

Examples of inheritance:

 

parent constructor     ->         child constructor   ->  lower levels

 

Object                                     String

Object                                     Array

Object                                     Date

Object                                     Number

Object                                     Event

Object                                     History

Node                                       Document

Node                                       Element                      HTML Element          Anchor

Node                                       Element                      HTML Element          Form

 

and so forth.  Object and Node are frequently used as a parent constructors.

 

 

***********************************************************

String() and Object() properties

 

So what property do we get when our constructor inherits from the Object() constructor?  It is:

 

constructor

 

So, when we build an object using the String() constructor,
we get two properties:

 

length        from the String() constructor

constructor   from the Object() constructor

 

The McDuffie and the Pollock books say that there is also a prototype property;
there is not a prototype property.  To get the prototype, go to the constructor function.  The constructor function object has the prototype property.

 

I do not want to talk about how prototypes work.

The constructor function has a related prototype.

The prototype is used to provide these properties to each object created by this function.  This allows all these objects to be modified by modifying the prototype.

This is weird.

 

 

***********************************************************

primitive string and String methods

 

If you have a primitive string, and try to use a String object method with it, it works!!!!  What happens is that the JavaScript interpreter automatically creates a String object, using the primitive string as the constructor parameter.  Then it uses this temporary String object with its method.

Amazing - JavaScript goes to great length to make anything work.

 

 

***********************************************************

String methods

 

There are several methods listed in your book.

We will discuss these, and two more additional methods.

The two additional methods are localCompare() and valueOf()

 

Several of the methods are standard methods, that are part of core JavaScript.

(Core JavaScript is those basic parts of JavaScript, that do not work with the web page.)

The standard core methods are:

 

-charAt()

-charCodeAt()

concat()

-indexOf()

-lastIndexOf()

localCompare()

match()

replace()

search()

slice()

split()

substring()

toString()

toLowerCase()

toUpperCase()

valueOf()

 

and the standard, static method:

 

fromCharCode()

It is a string method, but does not work with any specific string object.

 

substr()           is deprecated

 

Non-standard HTML methods are:

 

anchor()

big()

blink()

bold()

fixed()

fontcolor()

fontsize()

italics()

link()

small()

strike()

sub()

sup()

 

We will look at these in groups.

 

 

***********************************************************

String character methods

 

Look at unit 22 sample-2-character

 

It shows

 

charAt(1)                    returns a string containing the character at offset 1

                                    (counts from 0)

charCodeAt(10)        returns the ASCII (or UNICODE) character code of

the character at offset 10

indexOf("p")               returns the offset of the first "p"

lastIndexOf()               returns the offset of the last "p"

 

// sample-2-character.js
// This sample shows String character methods
 
function display()
  {
  var output1 = document.getElementById("output1");
  var output2 = document.getElementById("output2");
  var output3 = document.getElementById("output3");
  var output4 = document.getElementById("output4");
  var output5 = document.getElementById("output5");
  var output6 = document.getElementById("output6");
  var output7 = document.getElementById("output7");
 
  // String object
  my_string_object = new String("hippopotomas");
 
  output1.value = my_string_object;
  output2.value = my_string_object.length;
  output3.value = my_string_object.charAt(1);
  output4.value = my_string_object.charCodeAt(10);
  output5.value = my_string_object.indexOf("p");
  output6.value = my_string_object.lastIndexOf("p");
 
  // Note that fromCharCode is a static method.
  // It works with the String object,
  // not with my string object.
  output7.value = String.fromCharCode(104, 105, 112);
 
  }

 

 

***********************************************************

String substring methods

 

Look at unit 22 sample-3-substring

 

It shows

 

substring(3, 6)                                   copies character at offset 3, and stops

BEFORE character at 6

slice(-5, -3)                                         slice works like substring, but also allows
                                                            character counting from the end of the string.

                                                            -1 is the last character

concat(" ", my_string_object)           concatenates one or more strings and

                                                            String objects to a copy of the string.

 

primitive strings are constant, and cannot be changed.

Because the String objects contain a primitive string, they cannot be changed either.  So, none of the methods change the String object.

They just return a result

 

// sample-3-substring.js
// This sample shows String character methods
 
function display()
  {
  var output1 = document.getElementById("output1");
  var output2 = document.getElementById("output2");
  var output3 = document.getElementById("output3");
  var output4 = document.getElementById("output4");
  var output5 = document.getElementById("output5");
  var output6 = document.getElementById("output6");
  var output7 = document.getElementById("output7");
  var output8 = document.getElementById("output8");
 
  // String object
  my_string_object = new String("hippopotomas");
  a_string = new String("A");
 
  output1.value = my_string_object;
  output2.value = my_string_object.length;
 
  // substring includes the first character position,
  // to, but not including, the second character position
  // substring allows only positive numbers
  output3.value = my_string_object.substring(3, 6);
  // slice allows negative numbers, with -1 being
  // the last character.
  // Otherwise substring and slice are the same.
  output4.value = my_string_object.slice(-5, -3);
 
  output5.value = a_string;
  output6.value = a_string.concat(" ", my_string_object);
  output7.value = my_string_object;
  output8.value = a_string;
  }

 

 

***********************************************************

Case and string methods

 

Look at unit 22 sample-4-case

 

It shows

 

toLowerCase()                                  returns a copy of the string in small letters

toUpperCase()                                  returns a copy of the string in capital letters

toString()                                            returns a copy of the string

valueOf()                                             returns a copy of the string

implicit toString()                               returns a copy of the string

 

All objects have an implicit toString method, which produces something.

Sometimes they return a data string.

Sometimes they return a description of the object.

 

// sample-4-case.js
// This sample shows String case and string methods
 
function display()
  {
  var output1 = document.getElementById("output1");
  var output2 = document.getElementById("output2");
  var output3 = document.getElementById("output3");
  var output4 = document.getElementById("output4");
  var output5 = document.getElementById("output5");
 
  // String object
  my_string_object = new String("Zebra");
 
  output1.value = my_string_object.toLowerCase();
  output2.value = my_string_object.toUpperCase();
 
  // The following produce the same result
  output3.value = my_string_object;            // implicit conversion
  output4.value = my_string_object.toString();
  output5.value = my_string_object.valueOf();
  }

 

 

***********************************************************

Strings and Arrays

 

Look at unit 22 sample-5-array-string

 

It shows

 

String.split("-")                       splits a string into Array elements at the "-"
characters

Array. join("+")                       joins the Array elements into a string with

                                                the "+" character between elements

 

 

 

// sample-5-array-string.js
// This sample shows String case and string methods
 
function display()
  {
  var output1 = document.getElementById("output1");
  var output2 = document.getElementById("output2");
  var output3 = document.getElementById("output3");
 
  // String object
  my_string_object = new String("H-He-Li-Be-B-C-N-O-F-Ne");
  my_array_object  = new Array();
 
  my_array_object  = my_string_object.split("-");
 
  small_array = new Array();
 
  for (var i = 0; i < my_array_object.length; i++ )
    {
    small_array[i] = document.getElementById( "small" + eval(i) );
    small_array[i].value  = my_array_object[i];
    }
 
  string2 = new String( my_array_object.join("+") );
 
  output1.value = my_string_object;
  output2.value = my_array_object;
  output3.value = string2;
  }

 

 

***********************************************************

Regular expressions

 

The string methods match() search() replace() use regular expressions.

We will see only simple examples here.

 

One of the key techniques for processing strings is to use regular expressions. Regular expressions are used in JavaScript, perl, several Unix utilities, and other environments that process strings.


I recommend you take the CIS 18B Advanced UNIX/LINUX, which teaches Regular Expressions.

 

After you learn regular expressions, I recommend you read about these methods in Flanagan's book.


We have come to the point where you can begin to read Flanagan's book.

If you plan to continue using JavaScript, I recommend you buy a copy. It is kept up to date. It is precise and detailed. It has four main sections, all on JavaScript: 1) core discussion

2) html/xml/browser discussion

3) core reference

4) html/xml/browser reference.


JavaScript , The Definitive Guide, Fifth Edition by David Flanagan, 2006, O'Reilly ISBN-13: 978-0-596-10199-2

 

 

Look at unit 22 sample-6-regular-expressions

 

It shows

 

var a_pattern = new RegExp("a","i");         creates a wrapper object for a

regular expression

"a" - looking for the letter a

"i" - case insensitive

(string_object.match(a_pattern)                  looking for an "a" or "A" in the string

                                                                        returns true or false

string_object.search(a_pattern)                  finds the location of the first "a" or "A"

                                                                        returns the offset found

                                                                        returns -1 on failure to find an "a" or "A"

var global_a_pattern = new RegExp("a","g");       regular expression

                                                                        "a" - lower case a

                                                                        "g" - global - find them all

var replaced_string = string_object.replace(global_a_pattern, "A");

Replace all the lower case "a" characters with "A".

 

// sample-6-regular-expressions.js
// This sample shows String character methods
 
function reset_values()
  {
  var output1 = document.getElementById("output1");
  var output2 = document.getElementById("output2");
  var output3 = document.getElementById("output3");
  var output4 = document.getElementById("output4");
  var output5 = document.getElementById("output5");
 
  output1.value = null;
  output2.value = null;
  output3.value = null;
  output4.value = null;
  output5.value = null;
 
  output1.focus();
 
  }
 
function change_values()
  {
  var output1 = document.getElementById("output1");
  var output2 = document.getElementById("output2");
  var output3 = document.getElementById("output3");
  var output4 = document.getElementById("output4");
  var output5 = document.getElementById("output5");
 
  var string_object = new String(output1.value);
 
  output2.value = string_object;
 
  var a_pattern = new RegExp("a","i");  // a, case insensitive
 
  if (string_object.match(a_pattern) != null)
    output3.value = "yes";
  else
    output3.value = "no";
 
  var string_location = string_object.search(a_pattern);
  if (string_location != -1)
    output4.value = string_location;
  else
    output4.value = "none";
 
  var global_a_pattern = new RegExp("a","g");  // a, case sensitive, global
  var replaced_string = string_object.replace(global_a_pattern, "A");
  output5.value = replaced_string;
 
  }

 

 

***********************************************************

Compare

 

There is a localCompare() method. It can be used to support alphabets other than are used in American English. We can compare strings using the comparison operators:
"aa" < "ab"   "ac" > "ab"   "ab" == "ab"
are all true.

 

 

***********************************************************

HTML node methods

 

This section is optional. It shows some dynamic HTML node methods.

There are some non-standard String methods that will put a string within an HTML element. They are the following:
anchor() big() blink() bold() fixed() fontcolor() fontsize() italics() link() small() strike() sub() sup()
I suggest you may not want to use these.

Standard methods for managing HTML nodes include:
document.getElementById() document.createElement document.createTextNode() Node.appendChild() Node.removeChild()

A very well supported, and very popular non-standard way of managing HTML nodes is to modify the Node.innerHTML property.

The standard methods, and modification of innerHTML are shown in the sample.

 

 

Look at unit 22 sample-7-html

 

It shows

 

 

// sample-7-html.js
// This sample shows String character methods
 
// Reset the input element
function reset_values()
  {
  var output1 = document.getElementById("output1");
  output1.value = null;
  output1.focus();
  }
 
// Create HTML elements and put them in 
// the output div elements
function change_values()
  {
 
  // get the user's input string
  // text_from_1 is used in the following sections
  var output1 = document.getElementById("output1");
  var string_object = new String(output1.value);
  var text_from_1 = string_object.toString();
 
  // original text
  var outputx = document.getElementById("outputx");
  // a TextNode is another wrapper for a string
  // it is an HTML node, ready to put in the web page
  var my_text_x = document.createTextNode(text_from_1);
  if(outputx.childNodes.length > 0 )
    {
    // take out the old TextNode
    outputx.removeChild(outputx.firstChild);
    }
  // Put the new TextNode in the div
  outputx.appendChild(my_text_x);
 
  // bold text
  var outputy = document.getElementById("outputy");
  var bold_text_node = document.createTextNode(text_from_1);
  // create a b element
  var my_bold_node = document.createElement("b");
  // put the TextNode in the b element
  my_bold_node.appendChild(bold_text_node);
  if(outputy.childNodes.length > 0 )
    {
    outputy.removeChild(outputy.firstChild);
    }
  // put the b element in the div
  outputy.appendChild( my_bold_node );
 
 
  // Italic text
  var outputz = document.getElementById("outputz");
  // use the widely supported, but non-standard
  // innerHTML property to put the I and TextNode 
  // elements in the div
  outputz.innerHTML = "<i>"+text_from_1+"</i>";
 
 
  }

 

This stuff is optional.  It is not part of the material taught in this course.

It is an introduction to dynamic HTML, which uses these techniques.

 

 

***********************************************************

Summary

 

String is a wrapper class for a primitive string.

It has many useful methods.