You are here: Reference > JavaScript > core > objects > String

String object

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";
Did you find this example helpful? yes no
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;
Did you find this example helpful? yes no
Converting values to string literals:
    // number to string
var str = String (56);          // "56"
var str = "" + 56;              // "56"
var str = (56).toString ();     // "56"
var str = (56).toString (2);    // "111000" (binary)
var str = (56).toString (15);   // "38" (hexadecimal)
var str = (56).toString (36);   // "1k" (base of 36)

    // array to string
var arr = [10, -2, 20];
var str = String (arr);     // "10,-2,20"
var str = "" + arr;         // "10,-2,20"
var str = arr.toString ();  // "10,-2,20"
var str = arr.join (" + "); // "10 + -2 + 20"

    // others
var str = String (true);        // "true"
var str = "" + true;            // "true"
var str = String (false);       // "false"
var str = "" + false;           // "false"
var str = String (null);        // "null"
var str = "" + null;            // "null"
var str = String (undefined);   // "undefined"
var str = "" + undefined;       // "undefined"
Did you find this example helpful? yes no
Converting strings to numeric values (for details, see Number object and unary addition operator):
    // Number constructor
var num = Number ("10");        // 10
var num = Number ("010");       // 10
var num = Number ("-32.12");    // -32.12
var num = Number ("12e-2");     // 0.12 (exponential notation)
var num = Number ("0x10");      // 16 (hexadecimal base)
var num = Number ("zero");      // NaN

    // Unary addition operator
var num = +"10";                // 10
var num = +"010";               // 10
var num = +"-32.12";            // -32.12
var num = +"12e-2";             // 0.12 (exponential notation)
var num = +"0x10";              // 16 (hexadecimal base)
var num = +"zero";              // NaN
Did you find this example helpful? yes no

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
[position]
Returns the character at the specified position. Unfortunately, Internet Explorer does not support the [] operator on strings, use the cross-browser charAt method instead.
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.
If you want to set the Unicode character code of a character in a string, use the fromCharCode method.
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.
If you want to get the Unicode character code of a character in a string, use the charCodeAt method.
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 (regExpToFind)*
Performs a regular expression search within the current string and returns the results in an Array.
replace (regExpToFind, replaceTextOrFunc)*
Performs a regular expression search within the current string, replaces the matches with the string specified by the replaceTextOrFunc parameter and returns the result. The original string is not changed.
search (regExpToFind)*
Performs a regular expression search within the current string and returns the zero-based position of the first match. 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.
toSource ( )*
Returns a string representing the source code of the current string.
toString ( )*
Returns a string representing the value of the current string.
toUpperCase ()*
Returns a string that contains the text content of the current String object in upper-case.
trim ()*
93.510.55
Removes white spaces from the beginning and end of the current String object and returns the result. The original string is not changed.
trimLeft ()*
3.55
Removes white spaces from the beginning of the current String object and returns the result. The original string is not changed.
trimRight ()*
93.510.55
Removes white spaces from the end of the current String object and returns the result. The original string is not changed.
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 type="text/javascript"> 
        function ChangeToRed () {
            return "<span style='color:#FF0000;'>" + this.toString () + "</span>";
        }
        String.prototype.toRed = ChangeToRed;
    </script>
</head>
<body>
    <script type="text/javascript">
        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

[position]

Returns the character at the specified position. Unfortunately, Internet Explorer does not support the [] operator on strings, use the cross-browser charAt method instead.
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, returns undefined.
var str = "a custom string";
    // output: 
    //        's' in Firefox, Google Chrome, Safari and Opera
    //        'undefined' in Internet Explorer
document.write (str[4]);
Did you find this example helpful? yes no

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 sample string";
    //output: 65 (the code of 'A')
document.write (str.charCodeAt (0));
Did you find this example helpful? yes no
If you want to set the Unicode character code of a character in a string, use the fromCharCode method:
var str = "a custom string";
var A = String.fromCharCode (65);

    // replace the first character
str = A + str.substr (1);
    //output: "A custom string"
document.write (str);

    // replace the third character
str = str.substr (0, 2) + A + str.substr (3);
    //output: "A Austom string"
document.write (str);
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
How to set the Unicode character code of a character in a string:
var str = "a custom string";
    // the code of 'A' is 65
var A = String.fromCharCode (65);

    // replace the first character
str = A + str.substr (1);
    //output: "A custom string"
document.write (str);

    // replace the third character
str = str.substr (0, 2) + A + str.substr (3);
    //output: "A Austom string"
document.write (str);
Did you find this example helpful? yes no
If you want to get the Unicode character code of a character in a string, use the charCodeAt method:
var str = "A sample string";
    //output: 65 (the code of 'A')
document.write (str.charCodeAt (0));
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"));
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 (regExpToFind)

Performs a regular expression search within the current string and returns the results in an Array.
regExpToFind Required. Specifies a regular expression or a string for the search.
If a string value is specified, it will be converted into a regular expression before the search (see Creating a RegExp object). If you want to search for a simple substring, you can also use the indexOf and lastIndexOf methods.
Return value: Returns an Array of matching strings, or null if no match is found..
This example show how to find negative integers in a string:
var str = "23, -12, -3, 5";
var regExp = /-\d+/g;
var matches = str.match (regExp);
    // matches has two elements:
    // -12 and -3
for (var i = 0; i < matches.length; i++) {
    document.write (matches[i]);
    document.write ("<br />");
}
Did you find this example helpful? yes no

replace (regExpToFind, replaceTextOrFunc)

Performs a regular expression search within the current string, replaces the matches with the string specified by the replaceTextOrFunc parameter and returns the result. The original string is not changed.
regExpToFind Required. Specifies a regular expression or a string for the search.
If a string value is specified, it will be converted into a regular expression before the search (see Creating a RegExp object).
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.
Case-sensitive search:
var str = "One by one";
var re = /one/;
var newStr = str.replace (re, "two");
    // output: One by two
document.write (newStr);
Did you find this example helpful? yes no
Case-insensitive search:
var str = "One by one";
var re = /one/i;
var newStr = str.replace (re, "two");
    // output: two by one
document.write (newStr);
Did you find this example helpful? yes no
Searching and replacing all occurences:
var str = "One by one";
var re = /one/ig;
var newStr = str.replace (re, "two");
    // output: two by two
document.write (newStr);
Did you find this example helpful? yes no
Removing all uppercase letters:
var str = "aBc_dEf_23";
var re = /[A-Z]/g;
var newStr = str.replace (re, "");
    // output: ac_df_23
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 = Number (int1);
    int2 = Number (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 (regExpToFind)

Performs a regular expression search within the current string and returns the zero-based position of the first match. If no match is found, returns -1.
Note that the exec and test methods of the RegExp object provides similar functionality.
regExpToFind Required. Specifies a regular expression for the search.
If a string value is specified, it will be converted into a regular expression before the search (see Creating a RegExp object). If you want to search for a simple substring, you can also use the indexOf and lastIndexOf methods.
Return value: Returns the position of the first match.
Case-sensitive search:
var str = "One by one";
var pos = str.search (/one/);
    // output: 7
document.write (pos);
Did you find this example helpful? yes no
Case-insensitive search:
var str = "One by one";
var pos = str.search (/one/i);
    // output: 0
document.write (pos);
Did you find this example helpful? yes no
Get the longest prefix of a string that only contains alphabetical characters:
var str = "aBc_dEf_23";
var pos = str.search (/[^a-z]/i);
var prefix = str.substr (0, pos);
    // output: aBc
document.write (prefix);
Did you find this example helpful? yes no
For more information about regular expressions, please see the page for the Regular Expression (RegExp) object.

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. The returned Array contains both empty and non-empty pieces except when the split pattern is a regular expression in Internet Explorer before version 9. In that cases, the returned Array does not contain the empty pieces. See the examples below for details.
A commonly-used split operation:
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
The split method works differently in Internet Explorer before version 9 than in other browsers:
var str = "|1||2|";

    // always has 5 elements in all browsers
var arr = str.split ("|");
document.write ("length: " + arr.length + "<br/>");
document.write (arr.join (','));

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

    // 2 elements in IE before version 9,
    // 5 elements otherwise
var arr = str.split (/\|/);
document.write ("length: " + arr.length + "<br/>");
document.write (arr.join (','));
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

toSource ()

Returns a string representing the source code of the current string.
Return value: Returns a string representing the source code.
var str = "some text";
    //output: (new String("some text")) 
document.write (str.toSource ());
Did you find this example helpful? yes no

toString ()

Returns a string representing the value of the current string.
Return value: Returns a string representing the value.
var str = "some text";
    //output: some text 
document.write (str.toString ());
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

trim ()

93.510.55
Removes white spaces from the beginning and end of the current String object and returns the result. The original string is not changed.
Return value: Returns the trimmed string.
var str = " a b ";
if (str.trim) {
    var trimmed = str.trim ();
}
else {
    var reTrim = /^[\s\xa0]+|[\s\xa0]+$/g;
    var trimmed = str.replace (reTrim, "");
}

    //output: "a b"
document.write ('"' + trimmed + '"');
Did you find this example helpful? yes no

trimLeft ()

3.55
Removes white spaces from the beginning of the current String object and returns the result. The original string is not changed.
Return value: Returns the trimmed string.
var str = " a b ";
if (str.trimLeft) {
    var trimmed = str.trimLeft ();
}
else {
    var reTrim = /^[\s\xa0]+/g;
    var trimmed = str.replace (reTrim, "");
}

    //output: "a b "
document.write ('"' + trimmed + '"');
Did you find this example helpful? yes no

trimRight ()

3.55
Removes white spaces from the end of the current String object and returns the result. The original string is not changed.
Return value: Returns the trimmed string.
var str = " a b ";
if (str.trimRight) {
    var trimmed = str.trimRight ();
}
else {
    var reTrim = /[\s\xa0]+$/g;
    var trimmed = str.replace (reTrim, "");
}

    //output: " a b"
document.write ('"' + trimmed + '"');
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:
var str = String (32);
document.write (str); // output: 32
document.write ("<br />");

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

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

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

var str = String (undefined);
document.write (str); // 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