St

Strings in JavaScript

37 exercises

About Strings

A string is the JavaScript data type to store text data. There is no separate data type for an individual character.

Creating a String

You create a string literal by wrapping the text in single quotes or double quotes. On Exercism, single quotes are used.

'Hello, World!'
"Hello, World!"

Some special characters of the text need to be prefixed with a backslash \, see escape sequences on MDN.

const text = 'I\'m having fun.\nWhat about you?';
console.log(text);
// => I'm having fun.
// => What about you?

Besides single and double quotes, you can also create a string by wrapping the text in backticks. This syntax allows to include single or double quotes and even new lines without the need to escape them. It also allows to embed expressions, see Template Strings for more details.

`A multi-line string
with 'single quotes'
and "double quotes"`;

Strings as Lists of Characters

A string can be treated as a list of characters where the first character has index 0. You can access an individual character of the string using square brackets and the index of the letter you want to retrieve. Alternatively, there is also the charAt method.

'cat'[1];
// => 'a'

'cat'.charAt(2);
// => 't'

You can determine the number of characters in a string by accessing the length property.

'cat'.length;
// => 3

Concatenation and Methods

The simplest way to concatenate strings is to use the addition operator +.

'I like' + ' ' + 'cats.';
// => "I like cats."

Strings provide a lot of helper methods, see MDN Docs on String Methods for a full list. The following list shows some commonly used helpers.

Strings are Immutable

Applying the methods above will never change the original string. Instead a new string will be created and returned. Strings (and other primitive data types) are immutable in JavaScript. That also means you cannot assign a different character at some index using the bracket syntax shown above (like you would in arrays).

const str = 'cat';
str[1] = 'u'; // fails silently
console.log(str);
// => 'cat'
Edit via GitHub The link opens in a new window or tab

Learn Strings

Practicing is locked

Unlock 1 more exercise to practice Strings