The Complete Javascript Strings Reference

標簽: 瀏覽(15572)  日期:2007-05-29

The Complete Javascript Strings Reference

Filed: Tue, Apr 17 2007 under Programming|| Tags: reference javascript strings ajax json

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.

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

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

String Properties

All strings have a length property which return the length of the string.

  alpha = "abcdefghijklmnopqrstuvwxyz";
   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. As you move the mouse over each row it will be highlighted to make it easier to read the table. If you click on a method you will be taken to that method`s detailed instructions.

MethodIE VersionMozilla VersionNotes
charAt3.02.0Returns the character at index.
charCodeAt5.54.5Returns the Unicode Value.
concat4.04.0Joins Strings
fromCharCode4.04.0Creates a string from the supplied unicode integers.
indexOf3.02.0Finds position of a substring.
lastIndexOf3.02.0Finds position of a substring.
localeCompare5.5???Compares two strings.
replace4.04.0Replaces a substring within a string.
slice3.02.0Extracts a substring starting at the index.
split4.03.0Returns an array with the delimiter as the pivot.
substr3.02.0Extracts x characters of a String starting at Index
substring3.02.0Extracts a substring from index to ending Index
toLocaleLowerCase5.5???Converts a language-localized string to lower case
toLocaleUpperCase5.5???Converts a language-localized string to upper case
toLowerCase3.02.0Converts the string to lower case
toString---4.5Returns the String Object as a String
toString4.03.0Returns the String Object as a String
toUpperCase3.02.0Converts the string to upper case
valueOf4.03.0See toString()

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.

MethodIE VersionMozilla VersionNotes
match4.04.0Does a pattern search on a string.
replace4.04.0Replaces a substring within a string.
search4.04.0Searches 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.

MethodIE VersionMozilla VersionNotes
anchor3.02.0Creates an Anchor Tag for the string.
big3.02.0Wraps the string in HTML <big> tags.
blink3.02.0Wraps the string in HTML <blink> tags.
bold3.02.0Wraps the string in HTML <b> tags.
fixed3.02.0Wraps the string in HTML <tt> tags.
fontcolor3.02.0Wraps the string in HTML <font color=`{color}`> tags.
fontsize3.02.0Wraps the string in HTML <font size=`{size}`> tags.
italics3.02.0Wraps the string in HTML <i> tags.
link3.02.0Creates a hypertext link from the string.
small3.02.0Wraps the string in HTML <small> tags.
strike3.02.0Wraps the string in HTML <strike> tags.
sub3.02.0Wraps the string in HTML <sub> tags.
sup3.02.0Wraps the string in HTML <sup> tags.

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

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

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 upto 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

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

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

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

-------------------------------------------------
上一篇:The Complete Javascript Number Reference 下一篇:Mastering Javascript Arrays



  
Are you Bot? How you know that?ofcz no.