A string is the JavaScript data type to store text data.
You create a string by wrapping the text in single quotes or double quotes. On Exercism, single quotes are used.
'Hello, World!'
"Hello, World!"
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.
'cat'[1];
// => 'a'
You can determine the number of characters in a string by accessing the length
property.
'cat'.length;
// => 3
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.
toUpperCase
andtoLowerCase
- change the case of all characterstrim
- remove whitespace at the beginning and endincludes
,startsWith
andendsWith
- determine whether another string is part of the given stringslice
- extract a section of the string
Strings are immutable in JavaScript. So a "modification", e.g. by some of the methods above, will always create a new string instead.