JavaScript/Strings

From Wikibooks, open books for an open world
Jump to: navigation, search
Previous: Numbers Index Next: Dates

A string is a type of variable which stores a string (chain of characters).

Contents

[edit] Basic Use

To make a new string, you can make a variable and give it a value of new String().

var foo = new String();

But, most developers skip that part and use a string literal:

var foo = "my string";

After you have made your string, you can edit it as you like:

foo = "bar"; //foo = "bar"
foo = "barblah"; //foo = "barblah"
foo += "bar"; //foo = "barblahbar"

A string literal is normally delimited by the '  or "  character, and can normally contain almost any character. Common convention differs on whether to use single quotes or double quotes for strings. Some developers are for single quotes (Crockford, Amaram, Sakalos, Michaux) while others are for double quotes (NextApp, Murray, Dojo). Whichever method you choose, try to be consistent in how you apply it.

Due to the delimiters, it's not possible to directly place either the single or double quote within the string when it's used to start or end the string. In order to work around that limitation, you can either switch to the other type of delimiter for that case, or place a backslash before the quote to ensure that it appears within the string:

foo = 'The cat says, "Meow!"';
foo = "The cat says, \"Meow!\"";
foo = "It's \"cold\" today.";
foo = 'It\'s "cold" today.';

[edit] Properties and methods of the String() object

As with all objects, Strings have some methods and properties.

[edit] replace(text, newtext)

The replace() function returns a string with content replaced.

var foo = "microsoft rox";
var newString = foo.replace("rox", "sux")
alert(foo); //microsoft rox
alert(newString); //microsoft sux

As you can see, replace() doesn't actually do anything to the 'foo' object at all.

[edit] toUpperCase()

This function returns the current string in upper case.

var foo = "Hello!";
alert(foo.toUpperCase()); // HELLO!

[edit] toLowerCase()

This function returns the current string in lower case.

var foo = "Hello!";
alert(foo.toLowerCase()); // hello!

[edit] length()

Returns the length as an integer.

var foo = "Hello!";
alert(foo.length); // 6

[edit] substring(start[, end])

Substring extracts characters from the start position

"hello".substring(1); // "ello"

When the end is provided, they are extracted up to but not including the end position.

"hello".substring(1, 3); // "el"

[edit] Further reading


Previous: Numbers Index Next: Dates
Personal tools
Namespaces
Variants
Actions
Navigation
Community
Toolbox
In other languages
Sister projects
Print/export