JavaScript — Lesson 8

String Methods

Working with text using built-in string methods.

By Majed Qandeel · Jul 26, 2026 · Lesson 8 of 12

String Methods

JavaScript strings have many built-in methods for searching, modifying, and extracting text. Strings are immutable - methods always return a new string.

Length Property

const text = "Hello, World!"; text.length; // 13

Finding Text

const msg = "JavaScript is awesome!"; msg.indexOf("awesome"); // 15 (first match) msg.indexOf("x"); // -1 (not found) msg.lastIndexOf("a"); // 11 (last match) msg.includes("Script"); // true msg.startsWith("Java"); // true msg.endsWith("!"); // true

Extracting Parts

const str = "Hello, World!"; str.slice(0, 5); // "Hello" (start, end) str.slice(7); // "World!" (from index to end) str.slice(-6); // "World!" (negative = from end) str.substring(7, 12); // "World"

Transforming Text

const name = " Alice "; name.toUpperCase(); // " ALICE " name.toLowerCase(); // " alice " name.trim(); // "Alice" name.trimStart(); // "Alice " name.trimEnd(); // " Alice"

Replacing & Splitting

const msg = "I love cats"; msg.replace("cats", "dogs"); // "I love dogs" "aabbcc".replaceAll("b", "x"); // "aaxxcc" // split: string to array "apple,banana,orange".split(","); // ["apple", "banana", "orange"] ["a", "b", "c"].join("-"); // "a-b-c"

Template Literals

Use backticks for strings with embedded expressions and multi-line support.

const name = "Alice"; const age = 25; // With template literals console.log(`Hello, ${name}! Age: ${age}`); // Multi-line string const html = ` <h2>Welcome, ${name}</h2> <p>Age: ${age}</p> `;

Accessing Characters

const str = "Hello"; str[0]; // "H" str.charAt(4); // "o" str.charCodeAt(0); // 72 (Unicode code point)
Tip: Template literals are the modern way to build strings with variables. They replace messy string concatenation with + and support multi-line text.

Practice what you learned in the Deoit Editor — a free, browser-based code editor.

Open Editor →