Strings, Template Literals, and String Methods
11 min read
Strings in JavaScript
Strings are immutable sequences of UTF-16 code units. You can use single quotes, double quotes, or backtick template literals. Always be consistent — at CPCODELAB we recommend double quotes for source files.
Template Literals
Template literals (backtick strings) support expression interpolation with ${} and can span multiple lines without escape sequences.
javascript
const first = "Alice";
const last = "Smith";
const greeting = `Hello, ${first} ${last}!`;
// "Hello, Alice Smith!"
const multiline = `Line one
Line two
Line three`;Common String Methods
javascript
const str = " Hello, World! ";
str.trim(); // "Hello, World!"
str.trimStart(); // "Hello, World! "
str.trimEnd(); // " Hello, World!"
str.toLowerCase(); // " hello, world! "
str.toUpperCase(); // " HELLO, WORLD! "
const clean = str.trim();
clean.includes("World"); // true
clean.startsWith("Hello"); // true
clean.endsWith("!"); // true
clean.indexOf("o"); // 4
clean.lastIndexOf("o"); // 8
clean.slice(7, 12); // "World"
clean.replace("World", "JS"); // "Hello, JS!"
clean.replaceAll("l", "L"); // "HeLLo, WorLd!"
clean.split(", "); // ["Hello", "World!"]
"ha".repeat(3); // "hahaha"
"5".padStart(3, "0"); // "005"Strings are zero-indexed. str[0] gives the first character. str.length gives the number of UTF-16 code units, which can differ from the number of visible characters for emoji and some Unicode symbols.
Ready to test yourself?
Practice JavaScript— quiz & coding exercises