Notifications

No notifications

/Phase 2

Strings & Template Literals

Strings in JavaScript are immutable sequences of UTF-16 code units. You get three quote styles, dozens of helper methods, full Unicode support, and template literals — backtick strings with embedded expressions and multi-line text. This page covers the everyday toolkit plus a couple of common gotchas (Unicode length, replace only-first-match).

On this page

Detailed Theory

# Strings

Three quote styles

const a = 'single';
const b = "double";
const c = `backtick — supports ${interpolation} and
            multi-line text`;
Single vs double is purely style. Backticks are the modern default when you need interpolation or multiline.

Length & indexing

"hello".length;           // 5
"hello"[0];               // "h"  — strings are array-LIKE
"hello".charAt(0);        // "h"
"hello".at(-1);           // "o"  — negative indices, ES2022
⚠️ length counts UTF-16 *code units*, not characters: "😀".length is 2. Use [..."😀"].length for true character count.

Search & test

methodreturns
includes(s)true / false
startsWith(s), endsWith(s)true / false
indexOf(s) / lastIndexOf(s)index or -1
match(re), matchAll(re)regex matches

Slicing

"hello world".slice(0, 5);      // "hello"
"hello world".slice(-5);        // "world"   — negative supported
"hello world".substring(0, 5);  // "hello"   — older sibling, no negatives
"hello".split("");              // ["h","e","l","l","o"]
"a,b,,c".split(",");            // ["a","b","","c"]

Transform

"  Hello  ".trim();          // "Hello"
"hi".trimStart();  "hi".trimEnd();
"hi".padStart(5, "0");       // "000hi"
"hi".padEnd(5, ".");         // "hi..."
"abc".repeat(3);             // "abcabcabc"
"Hello".toUpperCase();
"Hello".toLowerCase();
"  a   b  ".replaceAll(/\s+/g, " ").trim();   // "a b"

replace vs replaceAll

"a-a-a".replace("a", "X");                  // "X-a-a"   ← only first!
"a-a-a".replace(/a/g, "X");                 // "X-X-X"
"a-a-a".replaceAll("a", "X");               // "X-X-X"   ES2021

Template literals — interpolation + multiline

const name = "Alice";
const age = 25;
const html = `
    <div>
        <h1>${name}</h1>
        <p>Age: ${age + 1} next year</p>
    </div>
`;
Any expression goes inside ${ … }.

Tagged templates

A function call where you tag the template:
function safe(strings, ...values) {
    return strings.reduce((out, s, i) =>
        out + s + (values[i] !== undefined ? escape(values[i]) : ""), "");
}
const out = safeHello, ${userInput}!;
Used by libraries (styled-components, GraphQL gql, Prisma raw queries).

Conversion

String(123);             // "123"
(123).toString();        // "123"
"" + 123;                // "123"   (works but less explicit)

Number("42"); // 42 parseInt("42px", 10); // 42 parseFloat("3.14kg"); // 3.14

Comparison & sorting

"abc" === "abc";                 // true (value equality, unlike objects)
"apple" < "banana";              // true (lexicographic)
["b","a","c"].sort();            // ["a","b","c"]
For locale-aware sort use a.localeCompare(b).

Regex basics — quick taste

/hello/i.test("Hello world");          // true (i = case-insensitive)
"abc123".match(/\d+/);                 // ["123"]
"foo bar".replace(/(\w+)/g, "<$1>");  // "<foo> <bar>"
Full regex deserves its own page; see MDN.

Strings are IMMUTABLE

let s = "hello";
s[0] = "H";              // silently ignored
console.log(s);          // "hello"

s = "H" + s.slice(1); // build a new string instead