Sie sind auf Seite 1von 22

The Complete Javascript Strings Reference

By Patrick Hunlock

Javascript Strings are deceptively complex constructs. There are actually two different types of
strings -- String Literals and String Objects -- and they both behave somewhat differently even
while trying to masquerade as the other. Strings, in addition to having some pretty funky
methods of dubious usefulness, have a great many oversights and shortcomings which can be
smoothed over with a few prototypes.
This reference will cover the difference between String Literals and String Objects, Strings'
properties and methods, some common and practical uses of Strings (particularly in regards to
JSON and AJAX), and offer a few, useful prototypes to extend the String class.

Literal or Object?
There are two different types of Strings and the behave quite differently. A literal is created just
by using quotes around your string. An object is created by implicit use of the new keyword. If
you assign a string to a variable using the String keyword, without the new keyword the contents
of the parenthesis will be cast as a string literal.
var StringLiteral = "This is a string Literal";
StringObject = new String("This is a string object");
StringTest = String(12345.68);

document.writeln(typeof(StringLiteral)+'<BR>'); // Outputs: string


document.writeln(typeof(StringObject)+'<BR>'); // Outputs: object
document.writeln(typeof(StringTest)+'<BR>'); // Outputs: string

A string literal has access to all of a string's objects and methods because Javascript will
temporarily cast a string literal as a string object in order to run the desired method.
var StringLiteral = "This is a string Literal";
StringObject = new String("This is a string object");
StringLiteral = StringLiteral.concat('!!!');
StringObject = StringObject.concat('###');

document.writeln(StringLiteral+'<BR>'); // Outputs: This is a string Literal!!!


document.writeln(StringObject+'<BR>'); // Outputs: This is a string object###

Where the two differ is their treatment of new properties and methods. Like all Javascript
Objects you can assign properties and methods to any String object.

The Complete Javascript Strings Reference Page 1 of 22


var alpha = new String("This is the first String Object");
var beta = new String("This is a second String Object");
var delta = "This is a String Literal";
alpha.property1 = 'This is private to alpha';
alpha.display = function () {
document.writeln('String: '+this+'<BR>');
document.writeln('Property: '+this.property1+'<BR>');
}
alpha.display();
// Outputs:
// String: This is the first String Object
// Property: This is private to alpha
beta.display();
// Generates an error since we never gave beta any
// properties or methods.
delta.display();
// Generates an error since we never gave the String
// prototype any properties or methods.

You can not add properties or methods to a string literal. They are ignored by the interpreter.
var alpha = "This is a string literal!";
alpha.property1 = 10;
alpha.method1 = function() { document.writeln('hello world!'); }

document.writeln(alpha.property1+'<BR>'); // outputs: undefined


alpha.method1(); // Generates an error.

The reason you can't add properties or methods to a string literal is that when you try to access a
literal's property or method, the Javascript interpreter temporarily copies the value of the string
into a new object and then use that object's properties or methods. This means a String literal
can only access a string's default properties or methods and those that have been added as
prototypes.
var alpha = new String("This is the first String Object");
var beta = new String("This is a second String Object");
var delta = "This is a String Literal";
String.prototype.property1 = 'This is public to all Strings Objects Or Literals';
String.prototype.display = function () {
document.writeln('String: '+this+'<BR>');
document.writeln('Property: '+this.property1+'<BR>');
}

alpha.display();
// Outputs:
// String: This is the first String Object
// Property: This is public to all Strings Objects Or Literals
beta.display();
// Outputs:
// String: This is the second String Object
// Property: This is public to all Strings Objects Or Literals
delta.display();
// Outputs:
// String: "This is a String Literal"
// Property: This is public to all Strings Objects Or Literals

The Complete Javascript Strings Reference Page 2 of 22


A final caveat is that literals and objects are treated differently by the eval statement.
var alpha = "2 + 2"; // alpha is a string literal
var beta = new String("2 + 2"); // beta is a string object
document.writeln(eval(alpha)+'<br>'); // Outputs: 4
document.writeln(eval(beta)+'<br>'); // Outputs: 2+2
document.writeln(eval(beta.valueOf())+'<br>'); // Outputs: 4

Strings Are Passed To Functions As Values


Unlike true objects and arrays, all strings (Literal or Objects) are passed to functions as values
which means anything you do to the string inside the function does not affect the original value.
var alpha = "This is a string literal";
beta = new String("This is a string object");

function changeString(strlit, strobj) {


var strlit='changed!!!';
var strobj='changed!!!';
}
changeString(alpha, beta);
document.writeln(alpha+'<br>'); // Outputs: This is a string literal
document.writeln(beta+'<br>'); // Outputs: This is a string object

Casting A String
You can cast data as a String through the use of the String command. When used in this way, the
String returns the content's valueOf result which is always a string. Additionally you can use
the plus sign to append a null string to the object, thus casting it as a string.
var numString = String(1234.36);
var numArray = String([1,2,3,4,5]);
var numObject = String({'color':'blue', 'song' : 'sung'});
var numString2= 1234.36 + '';
document.writeln(typeof(numString) + ' - ' + numString + '<br>');
document.writeln(typeof(numArray) + ' - ' + numArray + '<br>');
document.writeln(typeof(numObject) + ' - ' + numObject + '<br>');
document.writeln(typeof(numString2) + ' - ' + numString2 + '<br>');
// outputs:
// string - 1234.36
// string - 1,2,3,4,5
// string - [object Object]
// string - 1234.36

As you can see, casting an Object as a String returns an unexpected result. In Firefox you can get
around this with the Object's toSource() method, however this is not supported by Microsoft's
Internet Explorer or Opera.
var numObject = String({'color':'blue', 'song' : 'sung'}.toSource());
document.writeln(typeof(numObject) + ' - ' + numObject + '<br>');
//outputs (in Firefox):
//({color:"blue", song:"sung"})
// Generates an Error in Microsoft and Opera

The Complete Javascript Strings Reference Page 3 of 22


String Properties
All strings have a length property which return the length of the string.
var alpha = "abcdefghijklmnopqrstuvwxyz";
var beta = new String("abcdefghijklmnopqrstuvwxyz");

document.writeln(alpha.length+'<br>'); // Outputs: 26
document.writeln(beta.length+'<br>'); // Outputs: 26

String Method Reference (General Methods)


The following methods are a part of the String object and are available to String literals as well.

IE Mozilla
Method Notes
Version Version
charAt 3.0 2.0 Returns the character at index.
charCodeAt 5.5 4.5 Returns the Unicode Value.
concat 4.0 4.0 Joins Strings
fromCharCode 4.0 4.0 Creates a string from the supplied Unicode integers.
indexOf 3.0 2.0 Finds position of a substring.
lastIndexOf 3.0 2.0 Finds position of a substring.
localeCompare 5.5 ??? Compares two strings.
replace 4.0 4.0 Replaces a substring within a string.
slice 3.0 2.0 Extracts a substring starting at the index.
split 4.0 3.0 Returns an array with the delimiter as the pivot.
substr 3.0 2.0 Extracts x characters of a String starting at Index
substring 3.0 2.0 Extracts a substring from index to ending Index
toLocaleLowerCase 5.5 * Converts a language-localized string to lower case
toLocaleUpperCase 5.5 * Converts a language-localized string to upper case
toLowerCase 3.0 2.0 Converts the string to lower case
toString ** 4.5 Returns the String Object as a String
toString 4.0 3.0 Returns the String Object as a String
toUpperCase 3.0 2.0 Converts the string to upper case
valueOf 4.0 3.0 See toString()

* Undocumented Support
** Not supported

The Complete Javascript Strings Reference Page 4 of 22


String Method Reference (Regular Expressions)
These methods use regular expressions to do search and replace on strings. In general, methods
exist above which allow you to do without regular expression methods, however if you're
familiar with regular expressions you'll find these methods to be quick and easy (and in some
cases, a whole new can of worms/bugs). These methods are available to all strings be they
Objects or Literals.

Method IE Version Mozilla Version Notes


match 4.0 4.0 Does a pattern search on a string.
replace 4.0 4.0 Replaces a substring within a string.
search 4.0 4.0 Searches for a pattern within a string.

String Method Reference (HTML wrappers)


These methods aren't very useful since only a trivial few HTML tags are supported. It's like
someone started doing these then decided they were silly (which, for the most part, they are)
and stopped, but left what they had already done in interpreter where they became a part of the
language. These methods are available to all Strings whether Objects or Literals.

IE Mozilla
Method Notes
Version Version
anchor 3.0 2.0 Creates an Anchor Tag for the string.
big 3.0 2.0 Wraps the string in HTML <big> tags.
blink 3.0 2.0 Wraps the string in HTML <blink> tags.
bold 3.0 2.0 Wraps the string in HTML <b> tags.
fixed 3.0 2.0 Wraps the string in HTML <tt> tags.
fontcolor 3.0 2.0 Wraps the string in HTML <font color='{color}'> tags.
fontsize 3.0 2.0 Wraps the string in HTML <font size='{size}'> tags.
italics 3.0 2.0 Wraps the string in HTML <i> tags.
link 3.0 2.0 Creates a hypertext link from the string.
small 3.0 2.0 Wraps the string in HTML <small> tags.
strike 3.0 2.0 Wraps the string in HTML <strike> tags.
sub 3.0 2.0 Wraps the string in HTML <sub> tags.
sup 3.0 2.0 Wraps the string in HTML <sup> tags.

The Complete Javascript Strings Reference Page 5 of 22


String.anchor(nameAttribute)
This method creates an anchor attribute for the string. You supply an index value and the
method will return a HTML string, leaving the original string untouched.
var myString = "Table of Contents";
var htmlString=myString.anchor("TOC");
// htmlString = <A NAME="TOC">Table of Contents</A>

Supported Since IE 3.0, Netscape 2.0

String.big()
This method wraps the string in the HTML <big> tag (Big Text).
var myString = "Table of Contents";
var htmlString=myString.big(); // htmlString = <big>Table of Contents</big>
Supported Since IE 3.0, Netscape 2.0

String.blink()
This method wraps the string in the HTML <blink> tag. This actually exists! I am not making this
up!
var myString = "Table of Contents";
var htmlString=myString.blink(); // htmlString = <blink>Table of Contents</blink>

Supported Since IE 3.0, Netscape 2.0

String.bold()
This method wraps the string in the HTML <b> (bold) tag.
var myString = "Table of Contents";
var htmlString=myString.bold(); // htmlString = <b>Table of Contents</b>

Supported Since IE 3.0, Netscape 2.0

ab
The Complete Javascript Strings Reference Page 6 of 22
String.charAt(Index)
This method returns the character at a specific index starting with zero. If a string has a length of
26 then charAt's range is 0-25. Note that Firefox and Opera can achieve the same result with the
use of brackets, treating the string as a simulated array. Be warned, however, that addressing the
string as an Array will return undefined in Microsoft Internet Explorer. If you ask for a value
which is out of range (the 53rd position of a string that's only 26 characters long for instance)
this method will return an empty string (''), which is NOT the same as null. (test for an empty
string, not null).
alpha = "abcdefghijklmnopqrstuvwxyz";
beta = new String("abcdefghijklmnopqrstuvwxyz");

document.writeln(alpha.charAt(3)+'<br>'); // Outputs: d
document.writeln(beta.charAt(3)+'<br>'); // Outputs: d
document.writeln(alpha[3]+'<br>'); // Outputs: d, undefined in IE
document.writeln(beta[3]+'<br>'); // Outputs: d, undefined in IE
// Position out of range return an empty string.
document.writeln(alpha.charAt(53)+'<br>'); // Outputs: ''
document.writeln(beta.charAt(53)+'<br>'); // Outputs: ''

Supported Since IE 3.0, Netscape 2.0

String.charCodeAt(Index)
This method returns the Unicode value of the character at the requested index. This method
works the same as charAt() but instead of a character it returns a number representing the
Unicode value of the character. In very ancient versions of Javascript -- Netscape 4.0 and less,
Internet Explorer 5.0 and less -- this number represented the ISO-Latin-1 character set rather
than Unicode, however, the percentage of these browsers still in use today are so small it's
considered safe to assume a Unicode result. If you request an index which doesn't exist,
Javascript returns NaN (Not a Number, which is a Javascript reserved word/value in the same
vein as null and undefined).
alpha = "abcdefghijklmnopqrstuvwxyz";
beta = new String("abcdefghijklmnopqrstuvwxyz");

document.writeln(alpha.charAt(3)+'<br>'); // Outputs: 100


document.writeln(beta.charAt(3)+'<br>'); // Outputs: 100
// Position out of range return an empty string.
document.writeln(alpha.charAt(53)+'<br>'); // Outputs: NaN
document.writeln(beta.charAt(53)+'<br>'); // Outputs: Nan

Supported Since IE 5.5, Netscape 4.5

The Complete Javascript Strings Reference Page 7 of 22


String.concat(String[, String[, String...]])
The concat method joins the supplied strings to the original, returning a new string as a result.
You can also use the plus sign (+) to achieve the same effect. There is no difference between
string Objects and String Literals in the following example.
var alpha = " String 1 ";
var beta = " String 2 ";
var delta = " String 3 ";
newString1 = alpha + beta + delta;
newString2 = alpha.concat(beta, delta);
alpha += beta + delta;

document.writeln(newString1+'<br>'); // outputs: String 1 String 2 String 3


document.writeln(newString2+'<br>'); // outputs: String 1 String 2 String 3
document.writeln(alpha+'<br>'); // outputs: String 1 String 2 String 3

Numbers will be cast as strings for the concatenation. When using + to join strings, ANY string in
the equation will do a string concatenation on all the items which follow. That's a bit confusing
but say we have 5+20+42+"string", then the result will become 67 String, so we did straight
addition up to the string. AFTER the string, every addition becomes a string concatenation so
5+20+42+" string "+20+5 becomes 67 String 205. The second part of the equation becomes
string concatenation so 20 is appended with 5 instead of having 5 added to 20.
var alpha = "35";
var beta = 60;
newString1 = alpha + beta;
newString2 = alpha.concat(beta);
alpha += beta;
delta = 5+20+42+" String "+10+5;

document.writeln(newString1+'<br>'); // Outputs 3560


document.writeln(newString2+'<br>'); // Outputs 3560
document.writeln(alpha+'<br>'); // Outputs 3560
document.writeln(delta+'<br>'); // Outputs 67 String 105

Supported Since IE 4.0, Netscape 4.0

String.fixed()
This method wraps the string in the HTML <tt> tag (fixed-pitch font).
var myString = "Table of Contents";
var htmlString=myString.fixed();
// htmlString = <tt>Table of Contents</tt>

Supported Since IE 3.0, Netscape 2.0

The Complete Javascript Strings Reference Page 8 of 22


String.fontcolor(color)
This method wraps the string in the HTML <font color='{color}'> tag. Note that this method
violates Javascript's camelCase naming convention. fontcolor() is all lower case instead of
fontColor().
var myString = "Table of Contents";
var htmlString = myString.fontcolor('blue');
// htmlString = <font color="blue">Table of Contents</font>

Supported Since IE 3.0, Netscape 2.0

String.fontsize(size)
This method wraps the string in the HTML <font size='{size}'> tag. Note that this method violates
Javascript's camelCase naming convention. fontsize() is all lower case instead of fontSize().
There's a bit of funkiness here. If you use an integer as the size, you specify a size as one of 7 base
sizes. If you use a string as the integer, the size becomes relative to the <basefont> tag.
var myString = "Table of Contents";
var htmlString = myString.fontsize(7);
// htmlString = <font size="12">Table of Contents</font>

Supported Since IE 3.0, Netscape 2.0

String.fromCharCode(code1[, code#...])
This method accepts a series of Unicode characters and converts them to a Javascript string. This
method is a bit unusual in that its really more of a function than a String method since it doesn't
act on the data contained in the string. Because of this you don't need to use a string to access
this method, you can simply use the String object itself. Prior to IE 4.0 and Netscape 4.0, this
function converted ISO-Latin-1 codes.
var test = String.fromCharCode(112, 108, 97, 105, 110);
document.writeln(test); // outputs: plain

Supported Since IE 4.0, Netscape 4.0

ab
The Complete Javascript Strings Reference Page 9 of 22
String.indexOf(SearchValue[, startIndex])
IndexOf returns an index where the passed SearchValue was found or -1 if the search value was
not found. You can also supply an optional starting index (StartIndex) where the method will
start its search.
var alpha = 'The brown fox was faster than the white fox.';
var beta = new String('The brown fox was faster than the white fox.');
document.writeln(alpha.indexOf('fox')+'<br>'); // Outputs 10;
document.writeln(beta.indexOf('fox')+'<br>'); // Outputs 10;
// Now we'll start looking after the first position and get the second.
document.writeln(alpha.indexOf('fox',11)+'<br>'); // Outputs 40;
document.writeln(beta.indexOf('fox',11)+'<br>'); // Outputs 40;
// Look for something which isn't there.
document.writeln(beta.indexOf('bear')+'<br>'); // Outputs -1;

Supported Since IE 3.0, Netscape 2.0

String.italics()
This method wraps the string in the HTML <i> tag (italics).
var myString = "Table of Contents";
var htmlString=myString.italics();
// htmlString = <i>Table of Contents</i>

Supported Since IE 3.0, Netscape 2.0

String.lastIndexOf(SearchValue[, startIndex])
This method is the same as the indexOf method, however it searches from the end of the string
to the beginning of the string.
var alpha = 'The brown fox was faster than the white fox.';
var beta = new String('The brown fox was faster than the white fox.');
document.writeln(alpha.lastIndexOf('fox')+'<br>'); // Outputs 40;
document.writeln(beta.lastIndexOf('fox')+'<br>'); // Outputs 40;
// Now we'll start looking after the first position and get the second.
document.writeln(alpha.lastIndexOf('fox',39)+'<br>'); // Outputs 10;
document.writeln(beta.lastIndexOf('fox',39)+'<br>'); // Outputs 10;
// Look for something which isn't there.
document.writeln(beta.lastIndexOf('bear')+'<br>'); // Outputs -1;

Supported Since IE 3.0, Netscape 2.0

ab
The Complete Javascript Strings Reference Page 10 of 22
String.link(url)
This method creates a hypertext link for the string. You supply a URL as the first argument and
the method will return a HTML string, leaving the original string untouched.
var myString = "Table of Contents";
var htmlString=myString.link("http://www.hunlock.com");
// htmlString = <A HREF="http://www.hunlock.com">Table of Contents</A>

Supported Since IE 3.0, Netscape 2.0

String.localeCompare(string)
This IE specific method is supported by Firefox and Opera (support elsewhere may be spotty and
Opera returns unusual, but usable, results). This method compares the string with the passed
value. If the comparison string sorts lower than the original string then this method returns 1 (in
opera test for any positive value). If the two strings are equal, this method returns 0, and if the
comparison string sorts higher than the original string then this method returns -1 (Search for
any negative value in Opera).
Firefox 2.0 supports this method, however it is not documented so it's not possible to tell when
support for this method began. The documentation indicates that this comparison works
regardless of the language being used (Japanese for instance). Since this is not documented in
Firefox, the localization support may be imperfect.
var str = 'Hello Dolly!';
var result = str.localeCompare('Hello Dolly!');
document.writeln(result+'<br>'); // Outputs: 0
var result = str.localeCompare('Hello Bolly!');
document.writeln(result+'<br>'); // Outputs: 1
var result = str.localeCompare('Hello Molly!');
document.writeln(result+'<br>'); // Outputs: -1

Supported Since IE 5.5, Netscape (unknown, only unofficial support)

ab

The Complete Javascript Strings Reference Page 11 of 22


String.match(regExp)
The match method uses a regular expression to determine if a substring exists within the string.
If the substring exists it will return the substring. If you looked for multiple occurrences
(/string/g) and more than one result is found it will return an array containing all the matches.
Match takes 2x (best-case) as long to execute as IndexOf.
str = 'Now is the time for all good men to come to the aid of their country!';

result = str.match(/the/ig); // Look for "the" case insensitive (i), all occurrences (g)
document.writeln(result+'<br>'); // Outputs array: the, the, the

result = str.match(/^now/i); // Look for "now", case insensitive(i), start of string (^)
document.writeln(result+'<br>'); // Outputs array: Now

// Here we look for something that's not there -- "the" as the start of the string
// the result is null which means result will evaluate to false if we do...
// if not(result) { alert('we found nothing!'); }

result = str.match(/^the/i); // Look for "the" case insensitive(i), start of string (^)
document.writeln(result+'<br>'); // Outputs array: null

// The next example does pattern matching which, in this case, means we're looking for
// something that looks like a telephone number.

str = "Jenny's Number is 867-5309. At least back in the 80's";

result = str.match(/\d{3}-\d{4}/); // Search for 3 digits, dash, 4 digits


document.writeln(result+'<br>'); // Outputs: 867-5309

Supported Since IE 4.0, Netscape 4.0

String.replace(regExp/substr, replacementValue[, flags])


This is one of String's more complex methods, and correspondingly, one of the most powerful.
At its most simplest, this method will look for the supplied substring and, if found, replace it with
the supplied replacement string. The result of the replacement is returned as a new string. The
original string remains untouched.
str = "Jenny's Number is 867-5309. At least back in the 80's. The 80's were cool.";
result = str.replace("Jenny's", "Bob's"); // Replace Jenny's With Bob's
document.writeln(result);
// outputs:
//Bob's Number is 867-5309. At least back in the 80's. The 80's were cool.

This example works on a direct match. If we forgot to capitalized the J in Jenny, the replace would
fail.
str = "Jenny's Number is 867-5309. At least back in the 80's. The 80's were cool.";
result = str.replace("jenny's", "Bob's"); // Replace jenny's With Bob's
document.writeln(result);
// outputs:
//Jenny's Number is 867-5309. At least back in the 80's. The 80's were cool.

The Complete Javascript Strings Reference Page 12 of 22


(Firefox only) If we would like to ignore the case of the original string we can specify an optional
flag . The flags are...
g -- global, match more than one occurrence.
i -- case insensitive
m -- match over multiple lines ( useful for <pre> text. )
Here we'll supply an i flag so the previous example will work.
str = "Jenny's Number is 867-5309. At least back in the 80's. The 80's were cool.";
result = str.replace("jenny's", "Bob's", "i"); // Replace J/jenny's With Bob's
document.writeln(result);
// outputs:
//Bob's Number is 867-5309. At least back in the 80's. The 80's were cool.

If you would like to use the flags outside of Firefox you'll need to convert the search string to a
regular expression. This is actually pretty easy. Instead of using quotes, use forward slashes, and
at the end of the expression simply append the flags you would like the flag to use. In our above
example
result = str.replace("jenny's", "Bob's", "i"); // Replace J/jenny's With Bob's

becomes

result = str.replace(/jenny's/i, "Bob's"); // Replace J/jenny's With Bob's

In this next example we'll replace the with ***. Note that only the first occurrence will be replace
in the first example, but in the second, since we added a g flag (in addition to i) both occurrences
of the will be replaced.
str = "Jenny's Number is 867-5309. At least back in the 80's. The 80's were cool.";
result = str.replace(/the/i, "***"); // Replace "the" with "***", case insensitive
document.writeln(result);

// outputs:
//Jenny's Number is 867-5309. At least back in *** 80's. The 80's were cool.

str = "Jenny's Number is 867-5309. At least back in the 80's. The 80's were cool.";
result = str.replace(/the/ig, "***"); // Replace "the" with "***", case insensitive
document.writeln(result);

// outputs:
//Jenny's Number is 867-5309. At least back in *** 80's. *** 80's were cool.

If you opt to use a regular expression then you need to specify your flags as regular expression
modifiers instead of passing them as arguments. In Firefox, if you specify a regular expression, it
will ignore the flags arguments and instead look for the flags as part of the regular expression's
modifier.
A more powerful and practical example of a regular expression replace looks for something
resembling a telephone number and masks it out with # signs. The following example matches all
3 digit, dash, 4 digit patterns and replaces it with ###-####.

The Complete Javascript Strings Reference Page 13 of 22


str = "Jenny's Number is 867-5309. At least back in the 80's. The 80's were cool.";
result=str.replace(/[\d{3}\-\d{4}]+/,'###-####','g');
document.writeln(result);
// outputs:
// Jenny's Number is ###-####. At least back in the 80's. The 80's were cool.

You can use a function as the replacement value. The replace method will use the return value of
your function as the replacement value. It is unfortunate, but the arguments passed to your
function are not well thought out. If you used strings as your search criteria instead of regular
expressions then the parameters will always be
function myReplace(matchedSubstring, Index, OriginalString)

matchedSubstring will be the substring which was found and is going to be replaced. Index was
the numerical position the substring was found inside the string. OriginalString is the full
string that was searched. If you specified a g flag then your function will be called each time a
match was found.
The unfortunate part referred to earlier is that if you used a regular expression then
parenthetical matches will be inserted between the matchedSubstring and the Index, so there's
no constant you can use to refer to the Index or OriginalString save by using the argument's
array, which needlessly increases the complexity of the function.
Here we'll replace all numbers with either a (if less than or equal to 5) or b (if greater than 5).
We're using a regular expression as our search String, however since we're not using
parenthetical matches our function arguments will be constant.
function checkit(matchedSubstring, Index, OriginalString) {
if (matchedSubstring<=5) { return 'a' } else {return 'b'}
}
str = "Jenny's Number is 867-5309. At least back in the 80's. The 80's were cool.";
result=str.replace(/\d/g, checkit); // Search for any digits, call checkit for replacement
document.writeln(result);
// outputs:
//Jenny's Number is bbb-aaab. At least back in the ba's. The ba's were cool.

Finally, there are some special codes you can use in your replacement string
$$ -- Inserts a dollar sign.
$& -- Inserts the matched substring
$` -- Inserts the portion of the string which preceded the match.
$' -- Inserts the portion of the string which followed the match.
$n -- Inserts the Nth parenthesized substring match (assuming the first argument was a
regular expression and not a substring)
The following example takes all number groups and wraps them in brackets using the $&
replacement string.
str = "Jenny's Number is 867-5309. At least back in the 80's. The 80's were cool.";
result=str.replace(/(\d+)/g,'[$&]','g');
document.writeln(result);
// Outputs:
//Jenny's Number is [867-5309]. At least back in the [80]'s. The [80]'s were cool.

Supported Since IE 4.0, Netscape 4.0

The Complete Javascript Strings Reference Page 14 of 22


String.search(regExp)
This method accepts a regular expression as an argument and returns the index in the string
where the pattern was matched, or -1 if the pattern could not be matched. If more than one
occurrence of the pattern exists, only the first index will be returned.
This method is similar to indexOf except that it's twice as slow and doesn't allow more than one
item to be matched. So if possible, you should stick with indexOf.
str = "Once upon a time the big, bad ogre ate the goat, the mistral sang";
result=str.search(/(the)+/ig);
document.writeln(result); // outputs: 17
Supported Since IE 4.0, Netscape 4.0

String.slice(startIndex[, endIndex])
Slice will extract a substring starting at the specified starting index and ending at the specified
ending index. If endIndex is less than or equal to startIndex, the slice method will return a null
string. If endIndex is not specified the slice method will extract to the end of the string.
The original string is untouched.
str = "Jenny's Number is 867-5309.";
result = str.slice(8,14); // Contains: Number
result = str.slice(8); // Contains: Number is 867-5309.
result = str.slice(8,3); // Null
result = str.slice(100); // Null

Supported Since IE 3.0, Netscape 2.0

String.small()
This method wraps the string in the HTML <small> (Small Text)tag.
var myString = "Table of Contents";
var htmlString=myString.small(); // htmlString = <small>Table of Contents</small>
Supported Since IE 3.0, Netscape 2.0

String.split(delimiter[, limit])
This is one of the most powerful of the String methods. Given a delimiter as the first argument,
split() will create an array with each element containing an item separated by the delimiter in
the original string. That's a bit wordy so lets just show you the code
str = "One~Two~Three~Four";
newArray = str.split('~');
for(i=0; i<newArray.length; i++) {
document.writeln(i+'-'+newArray[i]+'<BR>');
}
// outputs:
// 0-One
// 1-Two
// 2-Three
// 3-Four

The Complete Javascript Strings Reference Page 15 of 22


The above example has a string with 5 words separated by the tilde (~) character. The split
breaks the string into an array using the tilde as the delimiter.
A very real world example is that you can use this method to receive an array from the server via
Ajax. You'll receive the array as a string with a unique delimiter just like in our example. By
running the string through the split method we have now reconstructed our array as it appears
on the server.
If you would like to manipulate a string as a true array (for speed or other reasons) then you can
easily convert a string to an array and then back again. To convert each index in a string to its
corresponding index in an Array just use a null string as a delimiter.
str='The quick brown fox';
newArray = str.split('');
for(i=0; i<newArray.length; i++) {
document.writeln(newArray[i]+', ');
}
//outputs:
//T, h, e, , q, u, i, c, k, , b, r, o, w, n, , f, o, x,

And to reverse the process use the Array's join() method with a null string.
str=newArray.join('');
document.writeln(str);
//outputs:
//The quick brown fox

Using the String method, split() and the Array method, join() you can easily manipulate
strings as arrays. String.split() can convert incoming AJAX data into arrays, and Array.join
can convert a Javascript array into a string ready to be sent to the server via Ajax (just use a
unique delimiter in your join method instead of a null string, as such)
toServer=newArray.join('~'); // Creates a string delimitated by tildies (~)

The optional limit parameter specifies how many array elements will be made. For instance if
you have a 30,000 character string and you only need the first 100 characters you would use
newArray = str.split('',100);

Supported Since IE 4.0, Netscape 3.0

String.strike()
This method wraps the string in the HTML <strike> (strikeout effect) tag.
var myString = "Table of Contents";
var htmlString=myString.strike(); //htmlString=<strike>Table of Contents</strike>
Supported Since IE 3.0, Netscape 2.0

The Complete Javascript Strings Reference Page 16 of 22


String.sub()
This method wraps the string in the HTML <sub> (subscript) tag.
var myString = "Table of Contents";
var htmlString=myString.sub();
// htmlString = <sub>Table of Contents</sub>
Supported Since IE 3.0, Netscape 2.0

String.substr(index[, numChars])
The substr() method is similar to the slice() method save that the second argument indicates
how many characters to include instead of an ending index. If numChars is not a positive number
then substr will return an empty string. If numChars is omitted, then substr will extract a string
from the index to the end of the string.
substr returns a new string. The original string is left untouched.
var str='The quick brown fox';
var speed = str.substr(4,5); // contains: quick
var speed = str.substr(4); // contains: quick brown fox
var speed = str.substr(4,-2); // contains: ''

Supported Since IE 3.0, Netscape 2.0

String.substring(index[, stopIndex])
This method is nearly identical to the slice() method. The only real difference is that if
stopIndex is less than index, instead of returning an empty string, substring() will extract the
string from the stopIndex to the Index (effectively reversing the numbers for you).
result = str.substring(8,14); // Contains: Number
result = str.substring(8); // Contains: Number is 867-5309.
result = str.substring(8,0); // Contains: Jenny's
result = str.substring(100); // Null
result = str.substring(100,0); // Contains: Jenny's Number is 867-5309.

Supported Since IE 3.0, Netscape 2.0

String.sup()
This method wraps the string in the HTML <sup> (superscript) tag.
var myString = "Table of Contents";
var htmlString=myString.sup();
// htmlString = <sup>Table of Contents</sup>

Supported Since IE 3.0, Netscape 2.0

The Complete Javascript Strings Reference Page 17 of 22


String.toLocaleLowerCase()
This method is intended to convert a string to lower case, regardless of the language being used.
Firefox 2.0 can use this method, however it does not appear in the official documentation
indicating that true international support may be imperfect.
var str = 'AbCdEfGhIjKlMnOpQrStUvWxYz';
var result = str.toLocaleLowerCase();
document.writeln(result);

// Outputs: abcdefghijklmnopqrstuvwxyz

Supported Since IE 5.5, Firefox (Unknown. Only unofficial support)

String.toLocaleUpperCase()
This method is intended to convert a string to upper case, regardless of the language being used.
Firefox 2.0 can use this method, however it does not appear in the official documentation
indicating that true international support may be imperfect.
var str = 'AbCdEfGhIjKlMnOpQrStUvWxYz';
var result = str.toLocaleUpperCase();
document.writeln(result);

// Outputs: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Supported Since IE 5.5, Firefox (Unknown. Only unofficial support)

String.toLowerCase()
This method simply returns the string as all lower case. The original string is left untouched.
( See also: toUpperCase() )
var str = 'AbCdEfGhIjKlMnOpQrStUvWxYz';
var result = str.toLowerCase();
document.writeln(result); // Outputs: abcdefghijklmnopqrstuvwxyz

Supported Since IE 3.0, Netscape 2.0

String.toSource()
This is a Firefox only method which will return a string that can be used to rebuild the string if
passed through an eval statement. Neither Internet Explorer or Opera support this method.
var str='AbCdEfGhIjKlMnOpQrStUvWxYz';
document.writeln(str.toSource());
// Outputs:
// (new String("AbCdEfGhIjKlMnOpQrStUvWxYz"))

Supported Since Netscape 2.0, Not supported in IE/Opera.

The Complete Javascript Strings Reference Page 18 of 22


String.toString()
This method overrides the default Object.toString() method. Your use of this method would
be fairly redundant.
strObj = new String("Hello World");
strLit = "Hello World";
document.writeln(strObj.toString()+'<br>'); // Outputs: Hello World
document.writeln(typeof(strObj.toString())+'<br>'); // Outputs: string
document.writeln(strLit.toString()+'<br>'); // Outputs: Hello World
document.writeln(typeof(strLit.toString())+'<br>'); // Outputs: string

Supported Since IE 4.0, Netscape 3.0

String.toUpperCase()
This method simply returns the string as all upper case. The original string is left untouched.
( See also: toLowerCase() )
var str = 'AbCdEfGhIjKlMnOpQrStUvWxYz';
var result = str.toLowerCase();
document.writeln(result); // Outputs: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Supported Since IE 3.0, Netscape 2.0

String.valueOf()
See String.toString()
Supported Since IE 4.0, Netscape 3.0

ab

The Complete Javascript Strings Reference Page 19 of 22


Converting Arrays To Strings For Ajax
If you need to send an array to a server through an Ajax call, you'll need to convert the array to a
string before you can do it. This is easy enough to do with the Array's join() method. Simply
pick a unique character that is unlikely to appear in your array. For this purpose a tilde (~) is
usually a safe character.
var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
var ajaxStr = myArray.join('~'); // contains: 1~2~3~4~5~6~7~8~9~10~11~12~13~14

You can now send ajaxStr to the server where it can be broken out into an array again.

Converting Strings into Arrays For Ajax


If you've received a string as an array via Ajax you'll need to convert that string back into an
array in Javascript. This is very simple to do! Just use the string's split() method to convert the
string into the array. In this example we'll assume the server used the tilde (~) as the delimiter.
var ajaxStr = "1~2~3~4~5~6~7~8~9~10~11~12~13~14"; // What we got from the server.
var myArray = ajaxStr.split('~'); // Turn the string into an Array
//MyArray now contains: 1,2,3,4,5,6,7,8,9,10,11,12,13,14;

Convert A String To JSON


To convert a string to JSON (Javascript Object Notation), you'll need to download and include the
public domainJSON library at http://www.json.org/json.js. In addition to giving you a
String.toJSONString() method, it also gives you methods for converting other data types as well.

Useful Prototypes
While the String methods in Javascript are powerful and useful, there is still room for
improvement and thanks to prototyping you can add whatever useful features you want!

Useful Prototypes: htmlEntities()


This method escapes all &, <, and > symbols in the string, making it safe to display the string on a
web page without fear that it will be treated as HTML.
String.prototype.htmlEntities = function () {
return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};

Usage
var tmp = '<html><head></head>';
var safe= tmp.htmlEntities(); // Returns &lt;html&gt;&lt;head&gt;&lt;/head&gt;

The Complete Javascript Strings Reference Page 20 of 22


Useful Prototypes: trim()
Removing leading and trailing whitespace is something which should have shipped with
Javascript from the start, but it's easy enough to make up for the designer's oversight.
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
return this.replace(/^\s+/g,"");
}
String.prototype.rtrim = function() {
return this.replace(/\s+$/g,"");
}

Usage
var test = " Test ";
var test1 = test.ltrim(); // returns "Test "
var test2 = test.rtrim(); // returns " Test"
var test3 = test.trim(); // returns "Test"

Useful Prototypes: stripTags()


This method will remove all < > tags (and everything in between), ensuring that the string
contains no HTML.
String.prototype.stripTags = function () {
return this.replace(/<([^>]+)>/g,'');
}

Usage
var tmp = '<a href="http://somespammer.com">Some Link</a>';
var safe= tmp.stripTags(); // Returns: Some Link;

Useful Prototypes: toArray()


This method explodes the string out into an array of characters.
String.prototype.toArray = function() {
return this.split('');
}

Usage
var str='AbCdEfGhIjKlMnOpQrStUvWxYz';
var arr=str.toArray();
for (var i=0; i<arr.length; i++) {
document.write(arr[i]+', ');
}
//Outputs:
//A, b, C, d, E, f, G, h, I, j, K, l, M, n, O, p, Q, r, S, t, U, v, W, x, Y, z,

The Complete Javascript Strings Reference Page 21 of 22


Useful Prototypes: toIntArray()
This method explodes the string out into an array of integers representing the character's
Unicode.
String.prototype.toIntArray = function() {
var returnArray = [];
for (var i=0; i<this.length; i++) {
returnArray.push(this.charCodeAt(i));
}
return returnArray;
}

Usage
var str='AbCdEfGhIjKlMnOpQrStUvWxYz';
var arr=str.toIntArray();
for (var i=0; i<arr.length; i++) {
document.write(arr[i]+', ');
}
// Outputs:
// 65, 98, 67, 100, 69, 102, 71, 104, 73, 106, 75, 108, 77,
// 110, 79, 112, 81, 114, 83, 116, 85, 118, 87, 120, 89, 122,

ab

Version
This document is current as of Firefox 2.03, IE 7.0, JSCRIPT 5.6, ECMA-262 Edition 3, Javascript 1.7

License
Copyright 2007 by Patrick Hunlock http://www.hunlock.com. The source code (but not the article
itself) in this document are released into the public domain and may be used without compensation
or attribution. Permission is granted to keep a copy for your own use, but all distribution rights are
reserved by the author.

The Complete Javascript Strings Reference Page 22 of 22