Strings in JavaScript
Strings are immutable sequences of UTF‑16 code units with rich methods and template literals for formatting.
Creating strings
Single, double, or backticks (template literals). Escape sequences like \n, \t are supported.
const a = 'hello'
const b = "hello"
const name = 'JS'
const c = `Hello, ${name}!` // interpolation
Common methods
' hi '.trim() // 'hi'
'a,b,c'.split(',') // ['a','b','c']
'test'.replace('t', 'T') // 'Test'
'go'.repeat(3) // 'gogogo'
'Hello'.toLowerCase()
'hello'.toUpperCase()
'hello'.includes('ell')
'hello'.startsWith('he')
'hello'.endsWith('lo')
Searching and substrings
const s = 'hello'
s.indexOf('l') // 2 (or -1)
s.lastIndexOf('l') // 3
s.slice(1, 3) // 'el'
s.substring(1, 3) // 'el' (no negative indexes)
Prefer slice for negative indices support.
Template literals and tags
Multiline and tagged templates.
const multi = `line 1\nline 2`
function tag(strings, ...values) { /* sanitize/format */ }
const out = tag`User: ${name}`
Unicode notes
JavaScript strings are UTF‑16; some characters use surrogate pairs (length 2).
const rocket = '🚀'
rocket.length // 2 (code units)
Array.from(rocket).length // 1 (code points)
Use Array.from, the spread operator, or for..of to iterate by code point.
Building strings efficiently
Use arrays + join for many concatenations or String.prototype.concat; template literals are concise.
const parts = []
for (let i = 0; i < 1000; i++) parts.push(String(i))
const big = parts.join(',')
Encoding/decoding
Use TextEncoder/TextDecoder for UTF‑8.
const enc = new TextEncoder().encode('café') // Uint8Array
const dec = new TextDecoder().decode(enc) // 'café'
Regex (preview)
Use RegExp or literals for pattern matching; see the RegExp section.
Summary
- Strings are immutable; use methods that return new strings
- Prefer template literals; handle Unicode code points carefully
- Use
TextEncoder/Decoderfor byte conversions