JavaScript String Object

From Techotopia
Revision as of 14:43, 5 May 2016 by Neil (Talk | contribs) (Text replacement - "<table border="0" cellspacing="0" width="100%">" to "<table border="0" cellspacing="0">")

Jump to: navigation, search
PreviousTable of ContentsNext
JavaScript Object BasicsJavaScript Date Object


Purchase and download the full PDF version of this JavaScript eBook for only $8.99


The JavaScript String Object is one of the most useful of the JavaScript Core Objects. It provides a range of methods that can be used to perform a variety of string manipulation tasks (replacing parts of a string with different text, extracting fragments of a string, finding where a particular character appears in a string and much, much more).


Contents


Creating a JavaScript String Object

An instance of a String object is created just as any other object instance is created (See JavaScript Object Basics). The object is created using the new keyword with the string to be used as the property passed through as the argument. For example:


myString = new String("This is my string");

JavaScript String object methods and properties are accessed using the standard object dot notation:

objectName.property

For example:


var stringLen = myString.length;

The above example returns the length of the string and assigns it to the variable stringLen.

Similarly, the following example returns the position index of the word my in the string (the word my begins at position 8 because the first character is always index position 0, not index position 1):


var position = myString.indexOf ("my");

To split a string up based on the locations of a specified delimiter (in this case the semi-colon):


myString = new String ("This is my string");

var stringArray = myString.split(";");

JavaScript String Object Methods

The following table lists the most commonly used methods built into the String object class:

MethodDescription
anchor(name)Creates an <a> tag of the form <a name="name>.
big()Increases the font size of the text by returning the string wrapped in HTML <big> and </big> elements (e.g. Example)
bold()Makes the string bold by returning the string wrapped in <b> and </b> elements (e.g. Example)
charAt(index)Returns the character at the specified index into the string. It is important to remember that the first character in a string in at index 0, not index 1.
concat(arg1, arg2 ...)Takes two or strings as arguments and combines them into a single string. Returns the combined string.
fixed()Returns the string ready to be displayed in fixed pitch (teletype style) font by wrapping the string in HTML <tt> and </tt> elements (e.g. Example)
fontcolor(color)Returns the string with a new foreground color by wrapping the string in HTML <font color="color"> and </font> elements (e.g. Example)
fontsize(size)Specifies the color of the string by wrapping the string in HTML <font size="size"> and </font> elements (e.g. Example)
indexOf(string, start)Takes a string as an argument and returns the index of the first occurrence of that string in an instance of a String object. The optional start argument specifies the index into the string where the search should begin. Returns -1 if no match to the string is found.
italics()Returns the string to be displayed in italics by wrapping the string in HTML <i> and </i> elements (e.g. Example)
lastIndexOf(string, start)Takes a string as an argument and returns the index of the last occurrence of that string in an instance of a String object. The optional start argument specifies the index into the string where the search should begin. Returns -1 if no match to the string is found.
link()Accepts a URL as an argument and constructs and returns an <a> tag using the URL as the href attribute.
match(regex)Accepts a regular expression (regex) as an argument and returns an array of matches found in the String object instance.
replace(regex, replacetext)Accepts two arguments: a regular expression and a replacement string. Replaces all matches to the regular expression in a String object instance with the replacement string provided. Returns -1 if no match is found.
search(regex)Accepts a regular expression as an argument and returns the index value of the location of the match in the String object. Returns -1 if no match is found.
slice(start, end)Accepts a start and an end index as arguments and returns the string fragment that is located between these two positions. End is optional. If not specified returns fragment from start index to end of string.
small()Makes the string smaller by returning it wrapped in the string in HTML <small> and </small> elements (e.g Example)
split(delimiter, limit)Accepts a delimiter and an optional limit as arguments and returns an array. This array contains the string broken up into fragments using the delimiter value to decide where to spit the string. The limit value allows the developer to impose a limit on how many fragments are returned
strike()Returns string wrapped in the string in HTML <strike> and </strike> elements to produce a strikeout effect (e.g Example)
sub()Returns string wrapped in the string in HTML <sub> and </sub> elements to produce a subscript effect (e.g. Example)
sup()Returns string wrapped in the string in HTML <sup> and </sup> elements to produce a superscript effect (e.g. Example)
substr(start, length)Accepts a start and length (number of characters) as arguments and returns the string fragment that is located between these two positions. length is optional. If not specified returns fragment from start index to end of string. If a negative index is passed through the index is referenced from the end of the string.
substring(start, end)Accepts a start and an end index as arguments and returns the string fragment that is located between these two positions. End is optional. If not specified returns fragment from start index to end of string.
toLowerCase()Returns the string with all characters converted to lower case
toUpperCase()Returns the string with all characters converted to upper case

JavaScript String Object Properties

PropertyDescription
lengthThe length of the string in characters
prototypeProvides a mechanism for developers to add properties to a string instance (see JavaScript Object Basics for details on extending objects).

JavaScript String Object Examples

Now that we are familiar with the methods and properties provided with the String object it is time to look at some examples. Before beginning, however, it is important to understand that the String Object methods do not modify the string contained in the object itself. Rather, a modified string is returned, leaving the original String object untouched.

After the following script fragment fragment is executed, myString still contains "This is my string". What the toUpperCase() method did was return the string converted to uppercase which was then assigned to variable upperCase. Therefore, the value of the string variable upperCase is now "THIS IS MY STRING":


myString = new String ("This is my string");
var upperCase = myString.toUpperCase();

Getting the length of a String Object

The length of a string object is obtained by accessing the length property:


myString = new String ("This is my string");
var stringLen = myString.length // assigns length of string to variable stringLen

Setting String Object text Effects

The JavaScript String object provides an extensive range of text effects. The script below shows how to use some of these:


myString = new String ("This is my string");

document.writeln ( myString.bold() );   // Displays text in bold

document.writeln ( myString.color("red"); // Displays text in red

document.writeln ( myString.italic());  // Displays text in italics

Performing Conversions on String Objects

The conversion methods of the String object are accessed in the same way as all other String object methods, and can be used to perform such tasks as converting the string to all upper case or all lower case.


myString = new String ("This is my string");
var upperCase = myString.toUpperCase();    // upperCase variable now contains 'THIS IS MY STRING'

myString = new String ("This Is My String");
var lowerCase = myString.toLowerCase();    // lowerCase variable now contains 'this is my string'

Manipulating Strings with the String Object

One of the most powerful features of the JavaScript String Object in the ability to manipulate strings. This includes breaking a string up into multiple sections, extracting fragments of a string and finding whether a particular string sequence is contained in a string.

To extract a single character from a specific index into the string:


myString = new String ("This is my string");
var thirdChar = myString.charAt(2);    // returns 'i' which is the third character (remember the first character is index 0!)

To extract a section of the string between two index points:


myString = new String ("This is my string");
var partString = myString.substring(5, 10);    // returns 'is my' which is the text between index points 5 and 10

To extract a given number of characters after an index point:


myString = new String ("This is my string");
var partString = myString.substr(5, 2);      // returns 'is' which is consists of the 2 characters after index point 5

To find where a particular string appears within a String object:


myString = new String ("This is my string");
var location = myString.indexOf ("my");      // returns 8 which is the index position where 'my' begins

location = myString.indexOf ("hello");      // returns -1 because myString does not contain the word "hello"

To replace part of the string with another string:


myString = new String ("This is my string");
var newString = myString.replace ("my", "your");   // returns 'This is your string'

Finally, to break a string up into multiple strings based on the locations of a specified delimiter, in this case a semi-colon:


myString = new String ("This is my string");

var stringArray = myString.split(";");

for (i=0; i<stringArray.length; i++)
{
        document.write ("Fragment " + i + " = " + stringArray[i]);
}

// outputs Fragment 0 = hello Fragment 1 = goodbye Fragment 2 = bonjour Fragment 3 = guten tag

Summary

In this chapter we have looked at one of the most powerful and frequently used JavaScript core objects - the String Object. As a JavaScript developer much of your time will be spent validating and manipulating string data entered by web site users. By combining the many methods of the String object it is possible to perform just about any string validation or manipulation tasks imaginable. As with any technology, experimentation is the key to getting up to speed on JavaScript Strings so fire up your favorite editor and start trying out the methods described above.


Purchase and download the full PDF version of this JavaScript eBook for only $8.99



PreviousTable of ContentsNext
JavaScript Object BasicsJavaScript Date Object