< JavaScript

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

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.';

Properties and methods of the String() object

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

concat(text)

The concat() function joins two strings.

var foo = "Hello";
var bar = foo.concat(" World!")
alert(bar);	// Hello World!

length

Returns the length as an integer.

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

indexOf

Returns the first occurrence of a string inside of itself, starting with 0. If the search string cannot be found, -1 is returned. The indexOf() method is case sensitive.

var foo = "Hello, World! How do you do?";
alert(foo.indexOf(' '));	// 6


var hello = "Hello world, welcome to the universe.";
alert(hello.indexOf("welcome"));      // 13

lastIndexOf

Returns the last occurrence of a string inside of itself, starting with index 0.. If the search string cannot be found, -1 is returned.

var foo = "Hello, World! How do you do?";
alert(foo.lastIndexOf(' '));	// 24

replace(text, newtext)

The replace() function returns a string with content replaced. Only the first occurrence is replaced.

var foo = "foo bar foo bar foo";
var newString = foo.replace("bar", "NEW!")
alert(foo);		// foo bar foo bar foo
alert(newString);	// foo NEW! foo bar foo

As you can see, the replace() function only returns the new content and does not modify the 'foo' object.

slice(start[, end])

Slice extracts characters from the start position.

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

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

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

Slice allows you to extract text referenced from the end of the string by using negative indexing.

"hello".slice(-4, -2);	// "el"

Unlike substring, the slice method never swaps the start and end positions. If the start is after the end, slice will attempt to extract the content as presented, but will most likely provide unexpected results.

"hello".slice(3, 1);	// ""

substr(start[, number of characters])

substr extracts characters from the start position, essentially the same as slice.

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

When the number of characters is provided, they are extracted by count.

"hello".substr(1, 3);	// "ell"

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"

substring always works from left to right. If the start position is larger than the end position, substring will swap the values; although sometimes useful, this is not always what you want; different behavior is provided by slice.

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

toLowerCase()

This function returns the current string in lower case.

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

toUpperCase()

This function returns the current string in upper case.

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

Escape Sequences

Escape sequences are very useful tools in editing your code in order to style your output of string objects, this improves user experience greatly.[1]

  • \b backspace (U+0008 BACKSPACE)
  • \f: form feed (U+000C FORM FEED)
  • \n: line feed (U+000A LINE FEED)
  • \r: carriage return (U+000D CARRIAGE RETURN)
  • \t: horizontal tab (U+0009 CHARACTER TABULATION)
  • \v: vertical tab (U+000B LINE TABULATION)
  • \0: null character (U+0000 NULL) (only if the next character is not a decimal digit; else it’s an octal escape sequence)
  • \': single quote (U+0027 APOSTROPHE)
  • \": double quote (U+0022 QUOTATION MARK)
  • \\: backslash (U+005C REVERSE SOLIDUS)

Further reading

  1. ↑ https://mathiasbynens.be/notes/javascript-escapes
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.