Professional Documents
Culture Documents
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);
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('###');
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.
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!'); }
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
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
document.writeln(alpha.length+'<br>'); // Outputs: 26
document.writeln(beta.length+'<br>'); // Outputs: 26
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
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.
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>
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>
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: ''
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");
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;
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>
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>
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
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;
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>
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;
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>
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
ab
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.
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.
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
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 ###-####.
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.
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
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
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);
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
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: ''
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.
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>
// Outputs: abcdefghijklmnopqrstuvwxyz
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
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
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"))
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
String.valueOf()
See String.toString()
Supported Since IE 4.0, Netscape 3.0
ab
You can now send ajaxStr to the server where it can be broken out into an array again.
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!
Usage
var tmp = '<html><head></head>';
var safe= tmp.htmlEntities(); // Returns <html><head></head>
Usage
var test = " Test ";
var test1 = test.ltrim(); // returns "Test "
var test2 = test.rtrim(); // returns " Test"
var test3 = test.trim(); // returns "Test"
Usage
var tmp = '<a href="http://somespammer.com">Some Link</a>';
var safe= tmp.stripTags(); // Returns: Some Link;
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,
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.