Basics
Introduction
Strings are immutable sequences of UTF-16 code units.
- String reference (developer.mozilla.org)
- Template literals (developer.mozilla.org)
Creating
const a = 'single'
const b = "double"
const c = `template ${a}` // → "template single"
const multi = `line one
line two`
String(42) // → "42"
String(null) // → "null"
See: Template literals, String() (developer.mozilla.org)
Accessing characters
'hello'.length // → 5
'hello'[1] // → 'e'
'hello'.at(-1) // → 'o'
'hello'.charAt(1) // → 'e'
'hello'.charCodeAt(1) // → 101
for (const ch of 'hi') {
console.log(ch) // logs "h", then "i"
}
Strings are immutable: methods return new strings, never change the original.
See: charAt(), String.prototype.at() (developer.mozilla.org)
Searching
'hello'.includes('ell') // → true
'hello'.startsWith('he') // → true
'hello'.endsWith('lo') // → true
'hello'.indexOf('l') // → 2
'hello'.lastIndexOf('l') // → 3
'hello'.indexOf('z') // → -1
Searches return -1 (or false) when the substring is absent.
See: includes(), startsWith(), indexOf() (developer.mozilla.org)
Extracting
'hamburger'.slice(3, 6) // → "bur"
'hamburger'.slice(-3) // → "ger"
'hamburger'.substring(6, 3) // → "bur" (args swapped)
'hamburger'.substr(3, 3) // → "bur" (deprecated)
slice() takes negative indexes; substring() clamps them to 0.
See: slice(), substring(), substr() (developer.mozilla.org)
Operations
Transforming
'Hi'.toUpperCase() // → "HI"
'Hi'.toLowerCase() // → "hi"
' pad '.trim() // → "pad"
' pad '.trimStart() // → "pad "
' pad '.trimEnd() // → " pad"
'ab'.repeat(3) // → "ababab"
'5'.padStart(3, '0') // → "005"
'5'.padEnd(3, '0') // → "500"
'e\u0301'.normalize('NFC') // → "é" (one code point)
See: toUpperCase(), trim(), padStart() (developer.mozilla.org)
Replacing
'a-b-c'.replace('-', '+') // → "a+b-c"
'a-b-c'.replaceAll('-', '+') // → "a+b+c"
'a-b-c'.replaceAll(/-/g, '+') // → "a+b+c"
'm-d'.replace(/(\w+)/, '[$1]') // → "[m]-d"
replace() changes the first match only; a regex given to replaceAll() must
have the g flag.
See: replace(), replaceAll() (developer.mozilla.org)
Splitting and joining
'a,b,c'.split(',') // → ["a", "b", "c"]
'foo'.concat('bar') // → "foobar"
['a', 'b'].join('-') // → "a-b"
'\u{1F600}'.split('').length // → 2 (UTF-16 units)
[...'\u{1F600}'].length // → 1 (code points)
split('') cuts code units, so surrogate pairs break; [...str] keeps them.
Comparing
'a' === 'a' // → true (compares by value)
'a' < 'b' // → true (code units)
'a'.localeCompare('b') // → -1
'B'.localeCompare('a') // → 1
'ABC'.toLowerCase() // → "abc"
localeCompare() returns a negative, zero, or positive number for sorting.
See: localeCompare() (developer.mozilla.org)
0 Comments for this cheatsheet. Write yours!