JavaScript Data Type: Strings

In JavaScript, the textual data is stored as strings. There is no separate type for a single character. Strings can be enclosed within either single quotes, double quotes or backticks.

Single and double quotes are essentially the same. Backticks allow to embed any expression into the string, by wrapping it in ${…}.

Special Characters

It is still possible to create multi-line strings with single and double quotes by using a newline character, written as \n, which denotes a line break.

String Length

The length property (not a function) has the string length. For example:

var str = 'abcdef';
alert('String Length: ' + str.length); // 6

Accessing Characters

To get a character at position pos, use square brackets [pos]. The first character starts from the zero position. For example:

var str = 'abcdef';
alert('Character at Third Position: ' + str[2]);

You can also iterate over characters using for..of:

for (var char of str)
{
alert(char); //a, b, c, d, e, f
}

Changing the Case

Methods toLowerCase() and toUpperCase() change the case. For example:

alert('Hello World'.toUpperCase()); // HELLO WORLD
alert('Hello World'.toLowerCase()); // hello world