JavaScript/Strings

From Wikibooks, the open-content textbooks collection

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. Because of 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 place a backslash before the quote to ensure that it appears within the string:

foo = "The cat says, \"Meow!\"";
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()

  • "hello".substring(1) => "ello"
    • Parameters: start position
  • "hello.substring(1,3) => "el"
    • Parameters: start position, end position

[edit] Further reading


Previous: Numbers Index Next: Dates
In other languages