Browse By Name
HTMLCSSJavaScriptAppendix
You are here: Reference > JavaScript > core > objects > String

String object

A A Font size Print Content Add new content Share Share
Browser support:
Represents series of characters as an object.
With the String object, you can get the length, characters and parts of a text, you can search and replace in texts and you can perform several other useful operations.

In JavaScript, the primitive string values (alias string literals) differ from the String object, their data type is string, not object. When you use strings in JavaScript, you work with primitive string values, not instances of the String object.

The JavaScript interpreter does not use the String object for implicit data type conversions (when a non-string value needs to be converted to a string, for example "32" + 2), but the String object can be used as a function to convert a value to a string literal explicitly. See Example 1 in the Some additional examples section for details.
When the JavaScript interpreter needs to convert a string literal to an object, it uses the String object. See Example 2 in the Some additional examples section for details.

Syntax:

Creating a new String object:
var newStr = new String (["chars"]);
Creating a new string literal:
var newStr = "chars";

Special characters:

An escape sequence means a backslash ('\') character followed by a character or a combination of digits. With escape sequences special characters can be placed into strings. An escape sequence always represents a single character.
In case of strings, the '\' (backslash) character has two different meanings, depending on the character that follows.
  • For an alphanumeric character, it indicates that it is a special character.
    Not every alphabetical character has a special meaning after a backslash. For example, the "n" string contains one n character - the "\n" string contains one new line character, but the "a" and "\a" strings are identical, they contain one a character.
  • For a non-alphanumeric character, it indicates that it is a normal character.
    It can be useful:
    if single and/or double quotes characters need to be used inside a string.
    For example, the "\'\"" string contains a single and a double quote character.
    if backslash characters need to be used inside a string.
    For example, the "\\" string contains one backslash character.
    if single and/or double quotes characters need to be used inside a string.
    For example, the "\'\"" string contains a single and a double quote character.
The following table contains the escape sequences that you can use in JavaScript strings.
\' single quote (Apostrophe)
\" Double quote
\\ Backslash
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Tab
\v Vertical tab
\ooo Octal digits that identify a character in Latin-1 encoding, between 0 and 377. (For example "\256" is the copyright sign).
\xhh Where the h hexadecimal digits identify a character in Latin-1 encoding, between 00 and FF. (For example "\xAE" is the copyright sign).
\uhhhh Where the h hexadecimal digits identify a character in the Unicode character table.
If a backslash character precedes a character that does not appear in the table above, then the escape sequence represents the character itself.
Some example:
  • The "n" string contains one n character - the "\n" string contains one new line character.
  • The "a" and "\a" strings are identical, they contain one a character.
  • The "\'\"" string contains a single and a double quote character
  • The "\\" string contains one backslash character.
  • The
    "123\
    456" string is identical to the "123456" string. If you need to break a string into multiple lines in the source code, use the backslash character at the end of the lines, within the string. The new line character closes a string by default, but if a backslash character precedes it, then the JavaScript interpreter jumps over it.
  • The "\x4D" string is identical to the "M" string, because the hexadecimal 4D (decimal 77) is the code of the 'M' character.
  • The "\061" string is identical to the "1" string, because the octal 61 (decimal 49) is the code of the '1' character.
  • The "\61" string is identical to the "1" string.
  • The "\612" string is identical to the "12" string, because the octal 612 is too large, but the octal 61 is allowed.
  • The "\8" string is identical to the "8" string, because 8 is not an octal digit.

String actions:

Creating a simple string variable:
var str = "the text that the string will contain";
Joining strings:
var str = "the text" + " that the string" + " will contain";

var str = "the text"; str = str + " that the string"; str = str + " will contain";

var str = "the text"; str += " that the string"; str += " will contain";

var str1 = "the text"; var str2 = " that the string will contain"; var str = str1 + str2;

Members:

The String object inherits from the String.prototype and Function.prototype objects. The following lists only contain the members of the String and String.prototype objects.

Properties:

Property Support Description
length*
Returns the number of characters in the current String object.
prototype
Returns a reference to the String.prototype object. The String.prototype object allows adding properties and methods to the String object that can be used with instances of the String object, like any predefined property or method. The prototype property is static, it cannot be accessed from an instance of the String object, only String.prototype is allowed.

(*) - The property is inherits from the String.prototype.

Methods:

Method Support Description
anchor (anchorName)*
Inserts the text content of the current String object into a named anchor element and returns the HTML source code of the tag. A named anchor element defines a destination anchor.
big ()*
Inserts the text content of the current String object into a big element and returns the HTML source code of the tag. The big element specifies that the enclosed text should be displayed in a 'large' font.
blink ()*
Inserts the text content of the current String object into a blink element and returns the HTML source code of the tag. The blink element specifies that the enclosed text should flash slowly.
bold ()*
Inserts the text content of the current String object into a b or strong element and returns the HTML source code of the tag. The b and strong elements specify that the enclosed text should be displayed in bold.
charAt (position)*
Returns the character at the specified position.
charCodeAt (position)*
Returns the Unicode encoding of the character at the specified position.
concat ([string1 [, string2 [, . . . [, stringN]]]])*
Appends the specified strings to the end of the current string and returns the concatenated string. The current String object is not changed.
fixed ()*
Inserts the text content of the current String object into a tt element and returns the HTML source code of the tag. The tt element specifies that the enclosed text should be displayed in a fixed-width font.
fontcolor (color)*
Inserts the text content of the current String object into a font element and returns the HTML source code of the tag. The fontcolor method also specifies the color property of the font element. A font element and its color property together specify that the enclosed text should be displayed in the given color.
fontsize (size)*
Inserts the text content of the current String object into a font element and returns the HTML source code of the tag. The fontcolor method also specifies the size property of the font element. A font element and its size property together specify that the enclosed text should be displayed in the given size.
fromCharCode ([code1 [, code2 [, ... [, codeN]]]])
Returns a concatenated string value from the given Unicode character codes. The fromCharCode method is static, it cannot be accessed from an instance of the String object, only String.fromCharCode is allowed.
indexOf (subString [, startIndex])*
Searches for a substring from a position within the current String object and returns the zero-based position of the first match. If no match is found, it returns -1. The search is case sensitive.
italics ()*
Inserts the text content of the current String object into an i element and returns the HTML source code of the tag. The i element specifies that the enclosed text should be displayed in italics.
lastIndexOf (subString [, startIndex])*
Searches for a substring backwards from a position within the current String object and returns the zero-based position of the first match. If no match is found, it returns -1. The search is case sensitive.
link (href)*
Inserts the text content of the current String object into an anchor element and returns the HTML source code of the tag. The anchor element displays the enclosed text as a hypertext link.
localeCompare (stringToCompare)*
Compares the current string with the specified string based on the browser default language settings and returns the result. The localeCompare method returns -1 if the current string is before the stringToCompare, returns 1 if the current string is after the stringToCompare and returns 0 if the two strings are identical. The comparison is case sensitive.
match (regExp)*
Performs a regular expression search within the current string, and returns the results in an Array.
replace (regExp, replaceTextOrFunc)*
Replaces the match of a regular expression with a string specified by the replaceTextOrFunc parameter and returns the result. The original string is not changed.
search (regExp)*
Returns the zero-based position of the first occurrence of the given regular expression. If no match is found, returns -1.
slice (startIndex, [endIndex])*
Returns the part of the current string between the given starting and end points.
small ()*
Inserts the text content of the current String object into a small element and returns the HTML source code of the tag. The small element specifies that the enclosed text should be displayed in a smaller font.
split ([separator [, limit]])*
Splits the current string into pieces at every occurrence of the given separator, and returns the result in an Array.
strike ()*
Inserts the text content of the current String object into a strike element and returns the HTML source code of the tag. The strike element specifies that the enclosed text should be displayed in strike-through type.
sub ()*
Inserts the text content of the current String object into a sub element and returns the HTML source code of the tag. The sub element specifies that the enclosed text should be displayed as subscripted text.
substr (startIndex [, length])*
Returns a part of the current string from a specified position with limited length.
substring (startIndex [, endIndex])*
Returns the part of the current string between the given start and end point.
sup ()*
Inserts the text content of the current String object into a sup element and returns the HTML source code of the tag. The sup element specifies that the enclosed text should be displayed as superscript text.
toLocaleLowerCase ()*
Returns a string that contains the text content of the current String object in lower-case. This method converts the alphabetic characters to lower-case based on the language settings of the browser.
toLocaleUpperCase ()*
Returns a string that contains the text content of the current String object in upper-case. This method converts the alphabetic characters to upper-case based on the language settings of the browser.
toLowerCase ()*
Returns a string that contains the text content of the current String object in lower-case.
toUpperCase ()*
Returns a string that contains the text content of the current String object in upper-case.
valueOf ()*
Returns a string literal representing the value of the String object.

(*) - The method is inherits from the String.prototype.

Properties

length

Returns the number of characters in the current String object.
var str = "my short string";
document.write (str.length); // display: 15
Did you find this example helpful? yes no

prototype

Returns a reference to the String.prototype object. The String.prototype object allows adding properties and methods to the String object that can be used with instances of the String object, like any predefined property or method. The prototype property is static, it cannot be accessed from an instance of the String object, only String.prototype is allowed.
<head>
    <script> 
        function ChangeToRed () {
            return "<span style='color:#FF0000;'>" + this.toString () + "</span>";
        }
        String.prototype.toRed = ChangeToRed;
    </script>
</head>
<body>
    <script>
        document.write ("The new method of the String object changes the " + "TEXT".toRed () + " to red.");
    </script>
</body>
Did you find this example helpful? yes no

Methods

anchor (anchorName)

Inserts the text content of the current String object into a named anchor element and returns the HTML source code of the tag. A named anchor element defines a destination anchor.
anchorName Required. String that specifies the name property of the anchor element.
Return value: String that contains the HTML source code.
var anchString = "Content of anchorTag";
    //output: <a name="anchorTag">Content of anchorTag</a>
document.write (anchString.anchor("anchorTag"));
Did you find this example helpful? yes no

big ()

Inserts the text content of the current String object into a big element and returns the HTML source code of the tag. The big element specifies that the enclosed text should be displayed in a 'large' font.
Return value: String that contains the HTML source code.
var bigStr = "Text to big";
    //output: <big>Text to big</big>
document.write (bigStr.big ());
Did you find this example helpful? yes no

blink ()

Inserts the text content of the current String object into a blink element and returns the HTML source code of the tag. The blink element specifies that the enclosed text should flash slowly.
Return value: String that contains the HTML source code.
var blinkStr = "Text to blink";
    //output: <blink>Text to blink</blink>
document.write (blinkStr.blink ());
Did you find this example helpful? yes no

bold ()

Inserts the text content of the current String object into a b or strong element and returns the HTML source code of the tag. The b and strong elements specify that the enclosed text should be displayed in bold.
Return value: String that contains the HTML source code.
var boldStr = "Text to bold";
    //output: <bold>Text to bold</bold>
document.write (boldStr.bold ());
Did you find this example helpful? yes no

charAt (position)

Returns the character at the specified position.
position Required. Zero-based integer that specifies the index of the character.
Return value: String that contains the character. If the position is not valid, it returns an empty string.
var str = "a custom string";
    //output: s
document.write (str.charAt (4));
Did you find this example helpful? yes no

charCodeAt (position)

Returns the Unicode encoding of the character at the specified position.
position Required. Zero-based integer that specifies the index of the character.
Return value: Returns an integer that identifies the character code. If the position is not valid, it returns the NaN global property.
var str = "a custom string";
    //output: 115
document.write (str.charCodeAt (4));
Did you find this example helpful? yes no

concat ([string1 [, string2 [, . . . [, stringN]]]])

Appends the specified strings to the end of the current string and returns the concatenated string. The current String object is not changed.
string1, ..., stringN Optional. Strings to concatenate.
Return value: Returns the combined string.
var str1 = "my first ";
var str2 = "combined ";
var str3 = "string";
var joinedStr = str1.concat (str2, str3);
    //output: my first combined string
document.write (joinedStr);
Did you find this example helpful? yes no

fixed ()

Inserts the text content of the current String object into a tt element and returns the HTML source code of the tag. The tt element specifies that the enclosed text should be displayed in a fixed-width font.
Return value: String that contains the HTML source code.
var fixedStr = "Text to show with fixed-width font.";
    //output: <tt>"Text to show with fixed-width font."</tt>
document.write (fixedStr.fixed ());
Did you find this example helpful? yes no

fontcolor (color)

Inserts the text content of the current String object into a font element and returns the HTML source code of the tag. The fontcolor method also specifies the color property of the font element. A font element and its color property together specify that the enclosed text should be displayed in the given color.
color Required. String that specifies the color property of the font element.
Return value: String that contains the HTML source code.
var redStr = "Text to show in red";
    //output: <font color="red">Text to show in red.</font>
document.write (redStr.fontcolor ("red"));
Did you find this example helpful? yes no

fontsize (size)

Inserts the text content of the current String object into a font element and returns the HTML source code of the tag. The fontcolor method also specifies the size property of the font element. A font element and its size property together specify that the enclosed text should be displayed in the given size.
size Required. String that specifies the size property of the font element.
Return value: String that contains the HTML source code.
var bigStr = "Big text";
    //output: <font size="7">Big text</font>
document.write (bigStr.fontsize (7));
Did you find this example helpful? yes no

fromCharCode ([code1 [, code2 [, ... [, codeN]]]])

Returns a concatenated string value from the given Unicode character codes. The fromCharCode method is static, it cannot be accessed from an instance of the String object, only String.fromCharCode is allowed.
code1, ..., codeN Optional. Integers that specify the Unicode character codes.
Return value: Returns the concatenated String.
var fixedStr = String.fromCharCode(83,65,77,80,76,69);
    //output: SAMPLE
document.write (fixedStr);
Did you find this example helpful? yes no

indexOf (subString [, startIndex])

Searches for a substring from a position within the current String object and returns the zero-based position of the first match. If no match is found, it returns -1. The search is case sensitive.
subString Required. String that specifies the text to search for.
startIndex Optional. Integer that specifies the start position of the search. Default is 0. Negative values mean start from the 0 position.
Return value: Integer, the position of the first occurrence, or -1 if no matching found.
var str = "a long long string";
    // output: 7, 
    // the start position of the second 'long' word,
    // because the search was started from the fourth character
document.write (str.indexOf ("long", 4));
Did you find this example helpful? yes no

italics ()

Inserts the text content of the current String object into an i element and returns the HTML source code of the tag. The i element specifies that the enclosed text should be displayed in italics.
Return value: String that contains the HTML source code.
var str = "Text to show in italic.";
    //output: <i>Text to show in italic.</i>
document.write (str.italics ());
Did you find this example helpful? yes no

lastIndexOf (subString [, startIndex])

Searches for a substring backwards from a position within the current String object and returns the zero-based position of the first match. If no match is found, it returns -1. The search is case sensitive.
subString Required. String that specifies the text to search for.
startIndex Optional. Integer that specifies the starting position of the search. Default is the last position within the current String object.
Return value: Integer, the position of the last occurrence, or -1 if no match is found.
var str = "a long long string";
    //output: 7, the start position of the second 'long' word
document.write (str.lastIndexOf ("long", 1));
Did you find this example helpful? yes no

link (href)

Inserts the text content of the current String object into an anchor element and returns the HTML source code of the tag. The anchor element displays the enclosed text as a hypertext link.
href Required. String that specifies the href property of the anchor element.
Return value: String that contains the HTML source code.
var str = "a HTML link";
    //output: <a href="sample.htm">an HTML link</a>
document.write (str.link ("sample.htm"));
Did you find this example helpful? yes no

localeCompare (stringToCompare)

Compares the current string with the specified string based on the browser default language settings and returns the result. The localeCompare method returns -1 if the current string is before the stringToCompare, returns 1 if the current string is after the stringToCompare and returns 0 if the two strings are identical. The comparison is case sensitive.
stringToCompare Required. String to compare.
Return value: Returns -1, 0 or 1.
-1 The given stringToCompare is sorted after the current string.
0 The two strings are equivalent.
1 The given stringToCompare is sorted before the current string.
var str = "original";
var strToCompare = "new";
    //output: 1, because 'new' is sorted before 'original'
document.write (str.localeCompare (strToCompare));
Did you find this example helpful? yes no

match (regExp)

Performs a regular expression search within the current string, and returns the results in an Array.
regExp Required. Specifies a regular expression for the search.
Return value: Returns an Array of matching strings.
var str = "man and woman are persons";
var regExp = /man/g;
var matching = str.match (regExp);
    //output: 'man,man'
document.write (matching);
Did you find this example helpful? yes no

replace (regExp, replaceTextOrFunc)

Replaces the match of a regular expression with a string specified by the replaceTextOrFunc parameter and returns the result. The original string is not changed.
regExp Required. Specifies a regular expression for the search.
replaceTextOrFunc Required. Specifies a text to insert in place of the occurrences or a reference to a function that will be called on each match.

If the replaceTextOrFunc parameter is a string, each match will be replaced with the specified string. The $n symbols have special meanings, they refer to the matching substrings of captured subexpressions. For further details, please see the examples below and the $1...$9 properties of the RegExp object.

If the replaceTextOrFunc parameter refers to a function, then this function will be called on each match. This function gets the current match as the first parameter, the matching substrings of captured subexpressions as the next parameters, then the zero-based character position of the match in the original string, and the complete original string as the last parameter. The function must return a string. This string will be inserted in place of the current match.

Return value: Returns the replaced string.
Searching and replacing only the first occurrence:
var str = "man and woman are persons";
var re = /(wo)?man/;
var newStr = str.replace (re, "person");
    // output: person and woman are persons
document.write (newStr);
Did you find this example helpful? yes no
Searching and replacing all occurences:
var str = "man and woman are persons";
var re = /(wo)?man/g;
var newStr = str.replace (re, "person");
    // output: person and person are persons 
document.write (newStr);
Did you find this example helpful? yes no
Using the $n symbols to convert a date to another format:
var re = /(\d{2})\W(\d{2})\W(\d{4})/;
var str = "06/12/2009";
var newStr = str.replace (re, "$3-$2-$1");
    // output: 2009-12-06  
document.write (newStr);
Did you find this example helpful? yes no
Using a funtion as a second parameter of the replace method to perform arithmetic operations in a string:
var str = "x = 2 + 3; y = 4 - 3;";
var newStr = str.replace (/(\d+)(\s*)(-|\+)(\s*)(\d+)/g, arit);
    // output: x = 5; y = 1; 
document.write (newStr);

/*
    match: the current match ('2 + 3' and '4 - 3')
    int1: first subexpression ( (\d+) : '2' and '4')
    ws1: second subexpression ( (\s*) : whitespaces)
    op: third subexpression ( (-|\+) : + and -)
    ws2: fourth subexpression ( (\s*) : whitespaces)
    int2: fifth subexpression ( (\d+) : '3' and '3')
    idx: the position of the match (4 and 15)
    origStr: the original string ("x = 2 + 3; y = 4 - 3;")
*/
function arit (match, int1, ws1, op, ws2, int2, idx, origStr) {
        // convert strings to numbers
    int1 = parseInt (int1);
    int2 = parseInt (int2);
        // process the operation
    if (op == '+') {
        var res = int1 + int2;
    }
    else {
        var res = int1 - int2;
    }

        // return the result as a string
    return "" + res;
}
Did you find this example helpful? yes no
For more information about regular expressions, please see the page for the Regular Expression (RegExp) object.

search (regExp)

Returns the zero-based position of the first occurrence of the given regular expression. If no match is found, returns -1.
Note that the exec and test methods of the RegExp object provides similar functionality.
regExp Required. Specifies a regular expression for the search.
Return value: Returns the position of the first match.
var str = "Apple is a fruit.";
    //output: 6
document.write (str.search (/is/));
Did you find this example helpful? yes no

slice (startIndex, [endIndex])

Returns the part of the current string between the given starting and end points.
startIndex Required. Specifies the zero-based position where the extraction begins.
endIndex Optional. Specifies the zero-based position where the extraction ends. If not specified, the end point is the length of the current string.
Return value: Returns the substring.
var str = "Anybody there?";
    //output: body
document.write (str.slice (3, 7));
Did you find this example helpful? yes no

small ()

Inserts the text content of the current String object into a small element and returns the HTML source code of the tag. The small element specifies that the enclosed text should be displayed in a smaller font.
Return value: String that contains the HTML source code.
var str = "some small content";
    //output: <small>some small content</small>
document.write (str.small ());
Did you find this example helpful? yes no

split ([separator [, limit]])

Splits the current string into pieces at every occurrence of the given separator, and returns the result in an Array. The split pieces do not contain the substrings matched by the separator.
separator Optional. Specifies a string or a regular expression for pattern matching. The matching is case sensitive for string separators.
limit Optional. Integer that specifies the maximum length of the returned Array.
Return value: Returns an Array of split strings.
var str = "apple, peach, cherry";
var arr = str.split (", "); 
    // The returned array has three elements:
    // apple | peach | cherry
for (var i = 0; i < arr.length; i++) {
    document.write (arr[i]);
    document.write ("<br />");
}
Did you find this example helpful? yes no

strike ()

Inserts the text content of the current String object into a strike element and returns the HTML source code of the tag. The strike element specifies that the enclosed text should be displayed in strike-through type.
Return value: String that contains the HTML source code.
var str = "some strike-through content";
    //output: <strike>some strike-through content</strike>
document.write (str.strike ());
Did you find this example helpful? yes no

sub ()

Inserts the text content of the current String object into a sub element and returns the HTML source code of the tag. The sub element specifies that the enclosed text should be displayed as subscripted text.
Return value: String that contains the HTML source code.
var str = "some subscripted text";
    //output: <sub>some subscripted text</sub>
document.write (str.sub ());
Did you find this example helpful? yes no

substr (startIndex [, length])

Returns a part of the current string from a specified position with limited length.
startIndex Required. Integer that specifies the zero-based position where the extraction begins.
length Optional. Integer that specifies the maximum number of returned characters. If not specified, the substr method returns the remaining part of the current string.
Return value: Returns the substring.
var str = "Anybody there?";
    //output: body
document.write (str.substr (3, 4));
Did you find this example helpful? yes no

substring (startIndex [, endIndex])

Returns the part of the current string between the given starting and end points.
startIndex Required. Integer that specifies the zero-based position where the extraction begins.
endIndex Optional. Integer that specifies the zero-based position where the extraction ends. If not specified, the substring method returns the remaining part of the current string.
Return value: Returns the substring.
var str = "Anybody there?";
    //output: body
document.write (str.substring (3, 7));
Did you find this example helpful? yes no

sup ()

Inserts the text content of the current String object into a sup element and returns the HTML source code of the tag. The sup element specifies that the enclosed text should be displayed as superscript text.
Return value: String that contains the HTML source code.
var str = "some superscripted text";
    //output: <sup>some superscripted text</sup>
document.write (str.sup ());
Did you find this example helpful? yes no

toLocaleLowerCase ()

Returns a string that contains the text content of the current String object in lower-case. This method converts alphabetic characters to lower-case based on the language settings of the browser.
Return value: Returns the lower-case string.
var str = "SOME TEXT";
    //output: some text
document.write (str.toLocaleLowerCase ());
Did you find this example helpful? yes no

toLocaleUpperCase ()

Returns a string that contains the text content of the current String object in upper-case. This method converts alphabetic characters to upper-case based on the language settings of the browser.
Return value: Returns the upper-case string.
var str = "some text";
    //output: SOME TEXT
document.write (str.toLocaleUpperCase ());
Did you find this example helpful? yes no

toLowerCase ()

Returns a string that contains the text content of the current String object in lower-case.
Return value: Returns the lower-case string.
var str = "SOME TEXT";
    //output: some text
document.write (str.toLowerCase ());
Did you find this example helpful? yes no

toUpperCase ()

Returns a string that contains the text content of the current String object in upper-case.
Return value: Returns the upper-case string.
var str = "some text";
    //output: SOME TEXT
document.write (str.toUpperCase ());
Did you find this example helpful? yes no

valueOf ()

Returns a string literal representing the value of the String object.
Return value: Returns a string literal.
var strObj = new String ("the string content");
var strLit = strObj.valueOf ();

document.write ("value of the String object: " + strObj);
document.write ("<br />");
document.write ("type of the String object: " + typeof (strObj));
document.write ("<br />");

document.write ("value of the string literal: " + strLit);
document.write ("<br />");
document.write ("type of the string literal: " + typeof (strLit));
document.write ("<br />");
Did you find this example helpful? yes no

Some additional examples:

Example 1:

Converts a value to a string literal explicitly with the String function:
x = String (32);
document.write (x); // output: 32
document.write ("<br />");

x = String (true);
document.write (x); // output: true
document.write ("<br />");

x = String (false);
document.write (x); // output: false
document.write ("<br />");

x = String (null);
document.write (x); // output: null
document.write ("<br />");

x = String (undefined);
document.write (x); // output: undefined
document.write ("<br />");
Did you find this example helpful? yes no

Example 2:

Adding a new method to the String object and calling it for a string literal:
String.prototype.getReverse = function () { 
            var reverse = "";
            for (var i = this.length - 1; i >= 0; i--) {
                reverse += this.charAt (i);
            }
            return reverse;
        };

    // "All right" is a string literal, not an instance of the String object,
    // but it will be converted to a String object before the getReverse method is called
var message = "All right".getReverse ();
document.write (message); // output: thgir llA

document.write ("<br />");

    // representing the same with an instance of the String object
var str = new String ("All right");
    // str is an instance of the String object
    // no conversion is needed
var message = str.getReverse ();
document.write (message); // output: thgir llA
Did you find this example helpful? yes no

External links:

User Contributed Comments

Post Content

Post Content