String

A primitive that represents a list of characters. Strings are immutable, indexable, and iterable.


Creating Strings

String literals

const str = 'Hello world';
str;
'Hello world'

String templates

const str = `answer: ${40 + 2}`;
str;
'answer: 42'

From other types

const str = String(4);
str;
'4'

Indexing

'abc'[0];
'a'
'abc'.at(-1);
'c'

Length

'abc'.length;
3

Comparing

<, <=, ===, >, and >= operators can be used.

'apple' < 'banana'
true
'apple' === 'apple'
true

.localeCompare(str) is a comparator

'apple'.localeCompare('banana');
-1
'apple'.localeCompare('apple');
0

Concatenation

'Hello' + 'World';
'HelloWorld'
['Hello', 'World'].join(' ');
'Hello World'

Searching

includes

'abcdef'.includes('cd');
true

indexOf

const str = 'abcdef';
str.indexOf('cd');
2
str.indexOf('z');
-1

Common Functions

split

'split on space'.split(' ');
['split', 'on', 'space']

slice

const str = 'abcdefg';
str.slice(0, 2);
'ab'
str.slice(1, 4);
'bcd'

Manage Casing

const str = 'Hello World';
str.toUpperCase();
'HELLO WORLD';
str.toLowerCase();
'hello world'

Replacing

'ab??d'.replace('?', 'c');
'abc?d'
'ab??d'.replaceAll('?', 'c');
'abccd'

Whitespace Trimming

'  whitespace   '.trim();
'whitespace'

Iterating

const str = 'abc';
for (let i = 0; i < str.length; i++) {
  console.log(str[i]);
}
a
b
c

A string is iterable.

for (const char of 'abc') {
  console.log(char);
}
a
b
c

External Resources