Browser/User Agent Support
| IE | Mozilla | Netscape | Opera | Safari | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
|---|
Constructors
| Constructor | IE | Mozilla | Netscape | Opera | Safari |
|---|---|---|---|---|---|
Constructs an instance of a String. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Properties
| Property | IE | Mozilla | Netscape | Opera | Safari |
|---|---|---|---|---|---|
Specifies the function that creates the String prototype. | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Number of characters in the string. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Reference to the String prototype object. | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Methods
| Method | IE | Mozilla | Netscape | Opera | Safari |
|---|---|---|---|---|---|
Returns a copy of a string as an HTML anchor. (e.g <a name="name"> | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns a copy of a string surrounded by <big></big> HTML tags. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | no |
Returns a copy of a string surrounded by <blink></blink> HTML tags. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns a copy of a string surrounded by <bold></bold> HTML tags. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns the specified character from a string. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns the the Unicode value of the character at the specified index. | 5.5+ | 1.0+ | 4.0+ | 7.0+ | 1.0+ |
Combines the text of two or more strings and returns a new string. | 4.0+ | 1.0+ | 4.0+ | 7.0+ | 1.0+ |
Returns a copy of a string surrounded by <tt></tt> tags. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns a copy of a string surrounded by <font color = "color"></font> tags. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns a copy of a string surrounded by <font size="size"></font> tags. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns a string created by using the specified sequence of Unicode values. | 4.0+ | 1.0+ | 4.0+ | 7.0+ | 1.0+ |
Returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex, or -1 if the value is not found. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns a copy of a string surrounded by <i></i> tags. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns the index within the calling
String object of the last occurrence of the
specified value, or -1 if not found. The calling string
is searched backward, starting at
fromIndex.
| 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns a copy of a string surrounded by <a href="href"></a> tags. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Uses locale-specific ordering to compare two strings. | 5.5+ | 1.0+ | 4.0+ | 7.0+ | 1.0+ |
Used to match a regular expression against a string. | 4.0+ | 1.0+ | 4.0+ | 7.0+ | 1.0+ |
Finds a match between a regular expression and a string, and replaces the matched substring with a new substring. | 3.0+ | 1.0+ | 4.0+ | 7.0+ | 1.0+ |
Executes the search for a match between a regular expression and this String object. | 4.0+ | 1.0+ | 4.0+ | 7.0+ | 1.0+ |
Extracts a section of a string and returns a new string. | 4.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns a copy of a string surrounded by <small></small> tags. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Splits a String object into an array of strings by separating the string into substrings. | 4.0+ | 1.0+ | 3.0+ | 7.0+ | no |
Returns a copy of a string surrounded by | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns a copy of a string surrounded by <sub></sub> tags. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns the characters in a string beginning at the specified location through the specified number of characters. | 4.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns a subset of a String object. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns a copy of a string surrounded by <sup></sup> tags. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns a copy of a string in lowercase letters in a locale-specific format. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | no |
Returns a copy of a string in uppercase letters in a locale-specific format. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | no |
Returns the string value converted to lowercase. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns a string representing the specified object. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns the string value converted to all uppercase. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Returns the primitive value of a String object. | 3.0+ | 1.0+ | 2.0+ | 7.0+ | 1.0+ |
Availability
JavaScript 1.0 | JScript 1.0 | ECMAScript v1
Constructor Detail
Property Detail
Object constructor - only
Specifies the function that creates the String prototype.
- See Also
- Availability
JavaScript 1.1 | JScript 2.0 | ECMAScript v1
Number length
Number of characters in the string.
-
The following example displays 8 in an Alert dialog box:
var x = "Netscape"; alert("The string length is " + x.length); - Remarks
-
This property returns the number of characters in the string. For an empty string,
lengthis 0. - Availability
JavaScript 1.0 | JScript 1.0 | ECMAScript v1
Object prototype - only
Reference to the String prototype object.
- Availability
JavaScript 1.1 | JScript 2.0 | ECMAScript v1
Method Detail
anchor(String name) : String
Returns a copy of a string as an HTML anchor. (e.g <a name="name">
| String | name | String to be copied into an HTML anchor. |
Example: Using
anchorThe following example code within an HTML
scriptelement:var myString = "Table of Contents"; document.writeln(myString.anchor("contents_anchor"));will output the following HTML:
<A NAME="contents_anchor">Table of Contents</A>
- Remarks
Use the
anchormethod with thedocument.writeordocument.writelnmethods to programmatically create and display an anchor in a document. Create the anchor with theanchormethod, and then callwriteorwritelnto display the anchor in a document. In server-side JavaScript, use thewritefunction to display the anchor.In the syntax, the text string represents the literal text that you want the user to see. The
nameAttributestring represents theNAMEattribute of the A tag.Anchors created with the
anchormethod become elements in thedocument.anchorsarray.- See Also
- Availability
JavaScript 1.0 | JScript 1.0 | ECMAScript v1
big() : String
Returns a copy of a string surrounded by <big></big> HTML tags.
-
Example: Using
bigThe following example uses
stringmethods to change the size of a string:var worldString="Hello, world" document.write(worldString.small()) document.write("<P>" + worldString.big()) document.write("<P>" + worldString.fontsize(7))This example produces the same output as the following HTML:
<P><SMALL>Hello, world</SMALL> <P><BIG>Hello, world</BIG> <P><FONTSIZE=7>Hello, world</FONTSIZE>
- Remarks
-
Use the
bigmethod with thewriteorwritelnmethods to format and display a string in a document. In server-side JavaScript, use thewritefunction to display the string. - See Also
- Availability
JavaScript 1.0 | JScript 1.0
blink() : String
Returns a copy of a string surrounded by <blink></blink> HTML tags.
Example: Using
stringmethods to change the formatting of a stringThe following example uses
stringmethods to change the formatting of a string:var worldString="Hello, world" document.write(worldString.blink()) document.write("<P>" + worldString.bold()) document.write("<P>" + worldString.italics()) document.write("<P>" + worldString.strike())This example produces the same output as the following HTML:
<P><BLINK>Hello, world</BLINK> <P><B>Hello, world</B> <P><I>Hello, world</I> <P><STRIKE>Hello, world</STRIKE>
- Remarks
Use the
blinkmethod with thewriteorwritelnmethods to format and display a string in a document. In server-side JavaScript, use thewritefunction to display the string.- See Also
- Availability
JavaScript 1.0 | JScript 1.0
bold() : String
Returns a copy of a string surrounded by <bold></bold> HTML tags.
-
Example: Using
stringmethods to change the formatting of a stringThe following example uses
stringmethods to change the formatting of a string:var worldString="Hello, world" document.write(worldString.blink()) document.write("<P>" + worldString.bold()) document.write("<P>" + worldString.italics()) document.write("<P>" + worldString.strike())This example produces the same output as the following HTML:
<P><BLINK>Hello, world</BLINK> <P><B>Hello, world</B> <P><I>Hello, world</I> <P><STRIKE>Hello, world</STRIKE>
- Remarks
-
Use the
boldmethod with thewriteorwritelnmethods to format and display a string in a document. In server-side JavaScript, use thewritefunction to display the string. - See Also
- Availability
JavaScript 1.0 | JScript 1.0
charAt(String index) : String
Returns the specified character from a string.
| String | index | An integer between 0 and 1 less than the length of the string. |
-
Displaying characters at different locations in a string
The following example displays characters at different locations in the string "
Brave new world":var anyString="Brave new world" document.writeln("The character at index 0 is " + anyString.charAt(0)) document.writeln("The character at index 1 is " + anyString.charAt(1)) document.writeln("The character at index 2 is " + anyString.charAt(2)) document.writeln("The character at index 3 is " + anyString.charAt(3)) document.writeln("The character at index 4 is " + anyString.charAt(4))These lines display the following:
The character at index 0 is B The character at index 1 is r The character at index 2 is a The character at index 3 is v The character at index 4 is e
- Remarks
-
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string called
stringNameisstringName.length - 1. If theindexyou supply is out of range, JavaScript returns an empty string. - See Also
- Availability
JavaScript 1.0 | JScript 1.0, ECMAScript v1
charCodeAt(Object index) : Number
Returns the the Unicode value of the character at the specified index.
| Object | index | An integer between 0 and 1 less than the length of the string. The default value is 0. |
-
Using
charCodeAtThe following example returns 65, the Unicode value for A.
"ABC".charCodeAt(0) // returns 65
- Remarks
-
Unicode values range from 0 to 65,535. The first 128 Unicode values are a direct match of the ASCII character set.
- See Also
- Availability
JavaScript 1.2 | JScript 5.5 | ECMAScript v1
concat(String string2...stringN) : String
Combines the text of two or more strings and returns a new string.
| String | string2...stringN | Strings to concatenate to this string. (one-or-more) |
-
Using
concatThe following example combines strings into a new string.
s1="Oh " s2="what a beautiful " s3="mornin'." s4=s1.concat(s2,s3) // returns "Oh what a beautiful mornin'."
- Remarks
concatcombines the text from one or more strings and returns a new string. Changes to the text in one string do not affect the other string.- See Also
- Availability
JavaScript 1.2 | JScript 3.0 | ECMAScript v3
fixed() :
Returns a copy of a string surrounded by <tt></tt> tags.
Example: Using
fixedto change the formatting of a stringThe following example uses the
fixedmethod to change the formatting of a string:var worldString="Hello, world" document.write(worldString.fixed())
This example produces the same output as the following HTML:
<TT>Hello, world</TT>
- Remarks
- Use the
fixedmethod with thewriteorwritelnmethods to format and display a string in a document. In server-side JavaScript, use thewritefunction to display the string. - Availability
JavaScript 1.0 | JScript 1.0
fontcolor(String color) : String
Returns a copy of a string surrounded by <font color = "color"></font> tags.
| String | color | A string expressing the color as either a hexadecimal RGB triplet or as a string literal. |
-
Example: Using
fontcolorThe following example uses the
fontcolormethod to change the color of a string:var worldString="Hello, world" document.write(worldString.fontcolor("maroon") + " is maroon in this line") document.write("<P>" + worldString.fontcolor("salmon") + " is salmon in this line") document.write("<P>" + worldString.fontcolor("red") + " is red in this line") document.write("<P>" + worldString.fontcolor("8000") + " is maroon in hexadecimal in this line") document.write("<P>" + worldString.fontcolor("FA8072") + " is salmon in hexadecimal in this line") document.write("<P>" + worldString.fontcolor("FF00") + " is red in hexadecimal in this line")The previous example produces the same output as the following HTML:
<P><FONT COLOR="maroon">Hello, world</FONT> is maroon in this line <P><FONT COLOR="salmon">Hello, world</FONT> is salmon in this line <P><FONT COLOR="red">Hello, world</FONT> is red in this line <P><FONT COLOR="8000">Hello, world</FONT> is maroon in hexadecimal in this line <P><FONT COLOR="FA8072">Hello, world</FONT> is salmon in hexadecimal in this line <P><FONT COLOR="FF00">Hello, world</FONT> is red in hexadecimal in this line
- Remarks
-
Use the
fontcolormethod with thewriteorwritelnmethods to format and display a string in a document. In server-side JavaScript, use thewritefunction to display the string.If you express color as a hexadecimal RGB triplet, you must use the format
rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".The
fontcolormethod overrides a value set in thefgColorproperty. - Availability
JavaScript 1.0 | JScript 1.0
fontsize(Number size) : String
Returns a copy of a string surrounded by <font size="size"></font> tags.
| Number | size | An integer between 1 and 7, or a string representing a signed integer between 1 and 7, specifiying what the font size should be set to. |
-
Example: Using
stringmethods to change the size of a stringThe following example uses
stringmethods to change the size of a string:var worldString="Hello, world" document.write(worldString.small()) document.write("<P>" + worldString.big()) document.write("<P>" + worldString.fontsize(7))This example produces the same output as the following HTML:
<P><SMALL>Hello, world</SMALL> <P><BIG>Hello, world</BIG> <P><FONT SIZE="7">Hello, world</FONT>
- Remarks
-
Use the
fontsizemethod with thewriteorwritelnmethods to format and display a string in a document. In server-side JavaScript, use thewritefunction to display the string.When you specify size as an integer, you set the size of
stringNameto one of the 7 defined sizes. When you specifysizeas a string such as "-2", you adjust the font size ofstringNamerelative to the size set in theBASEFONTtag. - See Also
- Availability
JavaScript 1.0 | JScript 1.0
fromCharCode(String num1, ..., numN) : static String
Returns a string created by using the specified sequence of Unicode values.
| String | num1, ..., numN | A sequence of numbers that are Unicode values. (one-or-more) |
-
Using
fromCharCodeThe following example returns the string "ABC".
String.fromCharCode(65,66,67)
- Remarks
-
This method returns a string and not a
Stringobject.Because
fromCharCodeis a static method ofString, you always use it asString.fromCharCode(), rather than as a method of aStringobject you created. - See Also
- Availability
JavaScript 1.2 | JScript 3.0 | ECMAScript v1
indexOf(String searchValue, [String fromIndex]) : Number
Returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex, or -1 if the value is not found.
| String | searchValue | A string representing the value to search for. |
| String | fromIndex | The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0. (optional) |
-
Using
indexOfandlastIndexOfThe following example uses
indexOfandlastIndexOfto locate values in the string "Brave new world".var anyString="Brave new world" // Displays 8 document.write("<P>The index of the first w from the beginning is " + anyString.indexOf("w")) // Displays 10 document.write("<P>The index of the first w from the end is " + anyString.lastIndexOf("w")) // Displays 6 document.write("<P>The index of 'new' from the beginning is " + anyString.indexOf("new")) // Displays 6 document.write("<P>The index of 'new' from the end is " + anyString.lastIndexOf("new"))indexOfand case-sensitivityThe following example defines two string variables. The variables contain the same string except that the second string contains uppercase letters. The first
writelnmethod displays 19. But because theindexOfmethod is case sensitive, the string "cheddar" is not found inmyCapString, so the secondwritelnmethod displays -1.myString="brie, pepper jack, cheddar" myCapString="Brie, Pepper Jack, Cheddar" document.writeln('myString.indexOf("cheddar") is ' + myString.indexOf("cheddar")) document.writeln('<P>myCapString.indexOf("cheddar") is ' + myCapString.indexOf("cheddar"));Using
indexOfto count occurrences of a letter in a stringThe following example sets
countto the number of occurrences of the letterxin the stringstr:count = 0; pos = str.indexOf("x"); while ( pos != -1 ) { count++; pos = str.indexOf("x", pos+1); } - Remarks
-
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character of a string called
stringNameisstringName.length - 1."Blue Whale".indexOf("Blue") // returns 0 "Blue Whale".indexOf("Blute") // returns -1 "Blue Whale".indexOf("Whale",0) // returns 5 "Blue Whale".indexOf("Whale",5) // returns 5 "Blue Whale".indexOf("",9) // returns 9 "Blue Whale".indexOf("",10) // returns 10 "Blue Whale".indexOf("",11) // returns 10The
indexOfmethod is case sensitive. For example, the following expression returns -1:"Blue Whale".indexOf("blue") - See Also
charAt | lastIndexOf | split
- Availability
JavaScript 1.0 | JScript 1.0, ECMAScript v1
italics() : String
Returns a copy of a string surrounded by <i></i> tags.
-
Example: Using
stringmethods to change the formatting of a stringThe following example uses
stringmethods to change the formatting of a string:var worldString="Hello, world" document.write(worldString.blink()) document.write("<P>" + worldString.bold()) document.write("<P>" + worldString.italics()) document.write("<P>" + worldString.strike())This example produces the same output as the following HTML:
<P><BLINK>Hello, world</BLINK> <P><B>Hello, world</B> <P><I>Hello, world</I> <P><STRIKE>Hello, world</STRIKE>
- Remarks
-
Use the
italicsmethod with thewriteorwritelnmethods to format and display a string in a document. In server-side JavaScript, use thewritefunction to display the string. - See Also
- Availability
JavaScript 1.0 | JScript 1.0
lastIndexOf(String searchValue, [String fromIndex]) : Number
Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. The calling string is searched backward, starting at fromIndex.
| String | searchValue | A string representing the value to search for. |
| String | fromIndex | The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is the length of the string. (optional) |
-
Using
indexOfandlastIndexOfThe following example uses
indexOfandlastIndexOfto locate values in the string "Brave new world".var anyString="Brave new world" // Displays 8 document.write("<P>The index of the first w from the beginning is " + anyString.indexOf("w")) // Displays 10 document.write("<P>The index of the first w from the end is " + anyString.lastIndexOf("w")) // Displays 6 document.write("<P>The index of 'new' from the beginning is " + anyString.indexOf("new")) // Displays 6 document.write("<P>The index of 'new' from the end is " + anyString.lastIndexOf("new")) - Remarks
-
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character is
stringName.length - 1."canal".lastIndexOf("a") // returns 3 "canal".lastIndexOf("a",2) // returns 1 "canal".lastIndexOf("a",0) // returns -1 "canal".lastIndexOf("x") // returns -1The
lastIndexOfmethod is case sensitive. For example, the following expression returns -1:"Blue Whale, Killer Whale".lastIndexOf("blue") - See Also
- Availability
JavaScript 1.0 | JScript 1.0, ECMAScript v1
link(String href) : String
Returns a copy of a string surrounded by <a href="href"></a> tags.
| String | href | String specifying the URL for the link. |
Example: Using
linkThe following example displays the word "Netscape" as a hypertext link that returns the user to the Netscape home page:
var hotText="Netscape" var URL="http://home.netscape.com" document.write("Click to return to " + hotText.link(URL))This example produces the same output as the following HTML:
Click to return to <A HREF="http://home.netscape.com">Netscape</A>
- Remarks
-
Use the
linkmethod to programmatically create a hypertext link, and then callwriteorwritelnto display the link in a document. In server-side JavaScript, use thewritefunction to display the link.Links created with the
linkmethod become elements in thelinksarray of thedocumentobject. Seedocument.links. - Availability
JavaScript 1.0 | JScript 1.0
localeCompare(String target) : Number
Uses locale-specific ordering to compare two strings.
| String | target | A string to be compared locale-wise to the string object. |
- Availability
JavaScript 1.5 | JScript 5.5 | ECMAScript v3
match(Object regexp) : Array
Used to match a regular expression against a string.
| Object | regexp | Name of the regular expression. It can be a variable name or a literal. |
-
Using
matchIn the following example,
matchis used to find "Chapter" followed by 1 or more numeric characters followed by a decimal point and numeric character 0 or more times. The regular expression includes theiflag so that case will be ignored.str = "For more information, see Chapter 3.4.5.1"; re = /(chapter \d+(\.\d)*)/i; found = str.match(re); document.write(found);
This returns the array containing Chapter 3.4.5.1,Chapter 3.4.5.1,.1
"
Chapter 3.4.5.1" is the first match and the first value remembered from(Chapter \d+(\.\d)*)."
.1" is the second value remembered from(\.\d).Using global and ignore case flags with
matchThe following example demonstrates the use of the global and ignore case flags with
match.str = "abcDdcba"; newArray = str.match(/d/gi); document.write(newArray);
The returned array contains D, d.
- Remarks
-
If the regular expression does not include the
gflag, returns the same result thatRegExp.execwould return on the regular expression and string. If the regular expression includes thegflag, returns an array of all the matches of the regular expression in the string.Note
If you execute a match simply to find true or false, use
String.searchor the regular expressiontestmethod. - See Also
RegExp | RegExp.exec | RegExp.test | String.replace | String.search
- Availability
JavaScript 1.2 | JScript 3.0 | ECMAScript v3
replace(String regexp, String newSubStr, String function) : Array
Finds a match between a regular expression and a string, and replaces the matched substring with a new substring.
| String | regexp | The name of the regular expression. It can be a variable name or a literal. |
| String | newSubStr | The string to put in place of the string found with regexp. |
| String | function | A function to be invoked after the match has been performed. |
-
Using
globalandignorewithreplaceIn the following example, the regular expression includes the global and ignore case flags which permits
replaceto replace each occurrence of 'apples' in the string with 'oranges'.re = /apples/gi; str = "Apples are round, and apples are juicy."; newstr=str.replace(re, "oranges"); document.write(newstr)
This prints "oranges are round, and oranges are juicy."
Defining the regular expression in
replaceIn the following example, the regular expression is defined in
replaceand includes the ignore case flag.str = "Twas the night before Xmas..."; newstr=str.replace(/xmas/i, "Christmas"); document.write(newstr)
This prints "Twas the night before Christmas..."
Switching words in a string
The following script switches the words in the string. For the replacement text, the script uses the
$1and$2replacement patterns.re = /(\w+)\s(\w+)/; str = "John Smith"; newstr = str.replace(re, "$2, $1"); document.write(newstr)
This prints "Smith, John".
Replacing a Fahrenheit degree with its Celcius equivalent
The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function returns 100C. If the number is 0F, the function returns -17.77777777777778C.
The regular expression
testchecks for any number that ends with F. The number of Fahrenheit degree is accessible to your function through the parameter$1. The function sets the Celsius number based on the Fahrenheit degree passed in a string to thef2cfunction.f2cthen returns the Celsius number. This function approximates Perl's s///e flag.function f2c(x) { var s = String(x) var test = /(\d+(?:\.\d*)?)F\b/g return s.replace (test, function (str,p1,offset,s) { return ((p1-32) * 5/9) + "C"; } ) } - Remarks
-
This method does not change the
Stringobject it is called on. It simply returns a new string.If you want to execute a global search and replace, include the
gflag in the regular expression.Specifying a string as a parameter
The replacement string can include the following special replacement patterns:
Pattern Inserts $$Inserts a "$". $&Inserts the matched substring. $`Inserts the portion of the string that precedes the matched substring. $ôInserts the portion of the string that follows the matched substring. $nor$nnWhere nornnare decimal digits, inserts the nth parenthesized submatch string.Specifying a function as a parameter
When you specify a function as the second parameter, the function is invoked after the match has been performed. (The use of a function in this manner is often called a lambda expression.)
In your function, you can dynamically generate the string that replaces the matched substring. The result of the function call is used as the replacement value.
The nested function can use the matched substrings to determine the new string (
newSubStr) that replaces the found substring. You get the matched substrings through the parameters of your function. The first parameter of your function holds the complete matched substring. The following n parameters can be used for parenthetical matches, remembered submatch strings, where n is the number of submatch strings in the regular expression. Finally, the last two parameters are the offset within the string where the match occurred and the string itself. For example, the followingreplacemethod returns XX.zzzz - XX , zzzz."XXzzzz".replace(/(X*)(z*)/, function (str, p1, p2, offset, s) { return str + " - " + p1 + " , " + p2; } ) - See Also
RegExp | RegExp.exec | RegExp.test | String.match | String.search
- Availability
JavaScript 1.2 | JScript 3.0 | ECMAScript v3
search(String regexp) : Number
Executes the search for a match between a regular expression and this String object.
| String | regexp | Name of the regular expression. It can be a variable name or a literal. |
-
Using
searchThe following example prints a message which depends on the success of the test.
function testinput(re, str){ if (str.search(re) != -1) midstring = " contains "; else midstring = " does not contain "; document.write (str + midstring + re.source); } - Remarks
-
If successful, search returns the index of the regular expression inside the string. Otherwise, it returns -1.
When you want to know whether a pattern is found in a string use
search(similar to the regular expressiontestmethod); for more information (but slower execution) usematch(similar to the regular expressionexecmethod). - See Also
RegExp | RegExp.exec | RegExp.test | String.match | String.replace
- Availability
JavaScript 1.2 | JScript 3.0 | ECMAScript v3
slice(String beginSlice, String endSlice) : String
Extracts a section of a string and returns a new string.
| String | beginSlice | The zero-based index at which to begin extraction. |
| String | endSlice | The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string. |
-
Using
sliceto create a new stringThe following example uses
sliceto create a new string.str1="The morning is upon us. " str2=str1.slice(3,-5) document.write(str2)
This writes:
morning is upon
- Remarks
-
sliceextracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string.sliceextracts up to but not includingendSlice.string.slice(1,4)extracts the second character through the fourth character (characters indexed 1, 2, and 3).As a negative index, endSlice indicates an offset from the end of the string. string.slice(2,-1) extracts the third character through the second to last character in the string.
- See Also
- Availability
JavaScript 1.2 | JScript 3.0 | ECMAScript v3
small() : String
Returns a copy of a string surrounded by <small></small> tags.
-
Example: Using
stringmethods to change the size of a stringvar worldString="Hello, world" document.write(worldString.small()) document.write("<P>" + worldString.big()) document.write("<P>" + worldString.fontsize(7))This example produces the same output as the following HTML:
<P><SMALL>Hello, world</SMALL> <P><BIG>Hello, world</BIG> <P><FONTSIZE=7>Hello, world</FONTSIZE>
- Remarks
- Use the
smallmethod with thewriteorwritelnmethods to format and display a string in a document. In server-side JavaScript, use thewritefunction to display the string. - See Also
- Availability
JavaScript 1.0 | JScript 1.0
split(String separator, [String limit]) : Array
Splits a String object into an array of strings by separating the string into substrings.
| String | separator | Specifies the character to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted, the array returned contains one element consisting of the entire string. |
| String | limit | Integer specifying a limit on the number of splits to be found. (optional) |
-
Using
splitThe following example defines a function that splits a string into an array of strings using the specified separator. After splitting the string, the function displays messages indicating the original string (before the split), the separator used, the number of elements in the array, and the individual array elements.
function splitString (stringToSplit,separator) { arrayOfStrings = stringToSplit.split(separator) document.write ('<P>The original string is: "' + stringToSplit + '"') document.write ('<BR>The separator is: "' + separator + '"') document.write ("<BR>The array has " + arrayOfStrings.length + " elements: ") for (var i=0; i < arrayOfStrings.length; i++) { document.write (arrayOfStrings[i] + " / ") } } var tempestString="Oh brave new world that has such people in it." var monthString="Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec" var space=" " var comma="," splitString(tempestString,space) splitString(tempestString) splitString(monthString,comma)This example produces the following output:
The original string is: "Oh brave new world that has such people in it." The separator is: " " The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it. / The original string is: "Oh brave new world that has such people in it." The separator is: "undefined" The array has 1 elements: Oh brave new world that has such people in it. / The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec" The separator is: "," The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec /
The difference between
splitin JavaScript 1.2 and other versionsConsider the following script:
str="She sells seashells \nby the\n seashore" document.write(str + "<BR>") a=str.split(" ") document.write(a)Using
LANGUAGE="JavaScript1.2", this script produces:"She", "sells", "seashells", "by", "the", "seashore"
Without
LANGUAGE="JavaScript1.2", this script splits only on single space characters, producing:"She", "sells", "seashells", "\nby", "the\n", "seashore"
Removing spaces from a string
In the following example,
splitlooks for 1 or more spaces followed by a semicolon followed by 1 or more spaces and, when found, removes the spaces from the string.nameListis the array returned as a result ofsplit.names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand "; document.write (names + "<BR>" + "<BR>"); re = /\s+;\s+/; nameList = names.split (re); document.write(nameList);
This prints two lines; the first line prints the original string, and the second line prints the resulting array.
Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand Harry Trump,Fred Barney,Helen Rigby,Bill Abel,Chris Hand
Returning a limited number of splits
In the following example,
splitlooks for 0 or more spaces in a string and returns the first 3 splits that it finds.myVar = " Hello World. How are you doing? "; splits = myVar.split(" ", 3); document.write(splits)This script displays the following:
["Hello", "World.", "How"
- Remarks
-
The
splitmethod returns the new array.When found,
separatoris removed from the string and the substrings are returned in an array. Ifseparatoris omitted, the array contains one element consisting of the entire string.In JavaScript 1.2 or later,
splithas the following additions:- It can take a regular expression argument, as well
as a fixed string, by which to split the object string.
If
separatoris a regular expression, any included parenthesis cause submatches to be included in the returned array.
- It can take a limit count so that the resulting array does not include trailing elements.
- If you specify
LANGUAGE="JavaScript1.2"in thescripttag,string.split(" ")splits on any run of 1 or more white space characters including spaces, tabs, line feeds, and carriage returns.
- It can take a regular expression argument, as well
as a fixed string, by which to split the object string.
If
- See Also
charAt | indexOf | lastIndexOf
- Availability
JavaScript 1.1 | JScript 3.0 | ECMAScript v1 | enhanced in ECMAScript v3
strike() : String
Returns a copy of a string surrounded by tags.
-
Example: Using
stringmethods to change the formatting of a stringThe following example uses
stringmethods to change the formatting of a string:var worldString="Hello, world" document.write(worldString.blink()) document.write("<P>" + worldString.bold()) document.write("<P>" + worldString.italics()) document.write("<P>" + worldString.strike())This example produces the same output as the following HTML:
<P><BLINK>Hello, world</BLINK> <P><B>Hello, world</B> <P><I>Hello, world</I> <P><STRIKE>Hello, world</STRIKE>
- Remarks
-
Use the
strikemethod with thewriteorwritelnmethods to format and display a string in a document. In server-side JavaScript, use thewritefunction to display the string. - See Also
- Availability
JavaScript 1.0 | JScript 1.0
sub() : String
Returns a copy of a string surrounded by <sub></sub> tags.
-
Example: Using
subandsupmethods to format a stringThe following example uses the
subandsupmethods to format a string:var superText="superscript" var subText="subscript" document.write("<P>This is what a " + superText.sup() + " looks like.") document.write("<P>This is what a " + subText.sub() + " looks like.")This example produces the same output as the following HTML:
<P>This is what a <SUP>superscript</SUP> looks like. <P>This is what a <SUB>subscript</SUB> looks like.
- Remarks
-
Use the
submethod with thewriteorwritelnmethods to format and display a string in a document. In server-side JavaScript, use thewritefunction to generate the HTML. - See Also
- Availability
JavaScript 1.0 | JScript 1.0
substr(Number start, Number length) : String
Returns the characters in a string beginning at the specified location through the specified number of characters.
| Number | start | Location at which to begin extracting characters (an integer between 0 and one less than the length of the string). |
| Number | length | The number of characters to extract. |
-
Using
substrConsider the following script:
str = "abcdefghij"; document.writeln("(1,2): ", str.substr(1,2)); document.writeln("(-2,2): ", str.substr(-2,2)); document.writeln("(1): ", str.substr(1)); document.writeln("(-20, 2): ", str.substr(1,20)); document.writeln("(20, 2): ", str.substr(20,2));This script displays:
(1,2): bc (-2,2): ij (1): bcdefghij (-20, 2): bcdefghij (20, 2):
- Remarks
-
startis a character index. The index of the first character is 0, and the index of the last character is 1 less than the length of the string.substrbegins extracting characters atstartand collectslengthnumber of characters.If
startis positive and is the length of the string or longer,substrreturns no characters.If
startis negative,substruses it as a character index from the end of the string. Ifstartis negative andabs(start)is larger than the length of the string,substruses 0 is the start index.If
lengthis 0 or negative,substrreturns no characters. Iflengthis omitted,startextracts characters to the end of the string. - See Also
- Availability
JavaScript 1.2 | JScript 3.0 | deprecated
substring(Number indexA, [Number indexB]) : String
Returns a subset of a String object.
| Number | indexA | An integer between 0 and one less than the length of the string. |
| Number | indexB | An integer between 0 and the length of the string. (optional) |
-
Using
substringThe following example uses
substringto display characters from the string "Mozilla":var anyString = "Mozilla"; // Displays "Moz" document.write(anyString.substring(0,3)); document.write(anyString.substring(3,0)); // Displays "lla" document.write(anyString.substring(4,7)); document.write(anyString.substring(7,4)); // Displays "Mozill" document.write(anyString.substring(0,6)); // Displays "Mozilla" document.write(anyString.substring(0,7)); document.write(anyString.substring(0,10));
Replacing a substring within a string
The following example replaces a substring within a string. It will replace both individual characters and substrings. The function call at the end of the example changes the string "
Brave New World" into "Brave New Web".function replaceString(oldS, newS, fullS) { // Replaces oldS with newS in the string fullS for (var i = 0; i < fullS.length; i++) { if (fullS.substring(i, i + oldS.length) == oldS) { fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length); } } return fullS; } replaceString("World", "Web", "Brave New World");JavaScript 1.2 "Out of Memory" error
In JavaScript 1.2, using
LANGUAGE="JavaScript1.2", the following script produces a runtime error (out of memory).var str = "Mozilla"; document.write(str.substring(0,3)); document.write(str.substring(3,0));
Without
LANGUAGE="JavaScript1.2", the above script prints the following:Moz Moz
In the second write, the index numbers are swapped.
- Remarks
-
substringextracts characters fromindexAup to but not includingindexB. In particular:- If
indexAis less than 0,indexAis treated as if it were 0.
- If
indexBis greater thanstringName.length,indexBis treated as if it werestringName.length.
- If
indexAequalsindexB,substringreturns an empty string.
- If
indexBis omitted,substringextracts characters to the end of the string.
In JavaScript 1.2
Using
LANGUAGE="JavaScript1.2"in thescripttag,- If
indexAis greater thanindexB, JavaScript produces a runtime error (out of memory).
Without
LANGUAGE="JavaScript1.2"in thescripttag,- If
indexAis greater thanindexB, JavaScript returnssubstring(indexB, indexA).
- If
- See Also
String.charAt | String.indexOf | String.lastIndexOf | String.slice | String.substr
- Availability
JavaScript 1.0 | JScript 1.0, ECMAScript v1
sup() : String
Returns a copy of a string surrounded by <sup></sup> tags.
-
Example: Using
subandsupmethods to format a stringThe following example uses the
subandsupmethods to format a string:var superText="superscript" var subText="subscript" document.write("<P>This is what a " + superText.sup() + " looks like.") document.write("<P>This is what a " + subText.sub() + " looks like.")This example produces the same output as the following HTML:
<P>This is what a <SUP>superscript</SUP> looks like. <P>This is what a <SUB>subscript</SUB> looks like.
- Remarks
-
Use the
supmethod with thewriteorwritelnmethods to format and display a string in a document. In server-side JavaScript, use thewritefunction to generate the HTML. - See Also
- Availability
JavaScript 1.0 | JScript 1.0
toLocaleLowerCase() : String
Returns a copy of a string in lowercase letters in a locale-specific format.
- See Also
String.toLocaleUpperCase | String.toLowerCase | String.toUpperCase
- Availability
JavaScript 1.5 | JScript 5.5, ECMAScript v3
toLocaleUpperCase() : String
Returns a copy of a string in uppercase letters in a locale-specific format.
- See Also
String.toLocaleLowerCase | String.toLowerCase | String.toUpperCase
- Availability
JavaScript 1.5 | JScript 5.5, ECMAScript v3
toLowerCase() : String
Returns the string value converted to lowercase.
-
Using
toLowerCaseThe following example displays the lowercase string "
alphabet":var upperText="ALPHABET" document.write(upperText.toLowerCase())
- Remarks
-
The
toLowerCasemethod returns the value of the string converted to lowercase.toLowerCasedoes not affect the value of the string itself. - See Also
- Availability
JavaScript 1.0 | JScript 1.0, ECMAScript v1
toString() : String
Returns a string representing the specified object.
-
Using
toStringThe following example displays the string value of a String object:
x = new String("Hello world"); alert(x.toString()) // Displays "Hello world" - Throws
- TypeError is thrown if the specified object is not a String.
- See Also
- Availability
JavaScript 1.0 | JScript 1.0, ECMAScript v1 Overrides Object.toString
toUpperCase() : String
Returns the string value converted to all uppercase.
Example: Using
toUpperCaseThe following example displays the string "
ALPHABET":var lowerText="alphabet" document.write(lowerText.toUpperCase())
- Remarks
The
toUpperCasemethod returns the value of the string converted to uppercase.toUpperCasedoes not affect the value of the string itself.- See Also
- Availability
JavaScript 1.0 | JScript 1.0 | ECMAScript v1
valueOf() : Object
Returns the primitive value of a String object.
Example: Using
valueOfx = new String("Hello world"); alert(x.valueOf()) // Displays "Hello world"- Remarks
-
The
valueOfmethod ofStringreturns the primitive value of a String object as a string data type. This value is equivalent to String.toString.This method is usually called internally by JavaScript and not explicitly in code.
- See Also
- Availability
JavaScript 1.0 | JScript 1.0 | ECMAScript v1
