JavaScript•Strings
JavaScript Strings: Template Literals, Regex, and Methods
Learn modern string manipulation, string interpolation, multiline text, and regular expression replacement.
Syntax
const str = "Hello World";
const replaced = str.replace("World", "Compilra");
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| split(delim) | Method | Divides string into an ordered list of substrings. |
| trim() | Method | Removes leading and trailing whitespace. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing JavaScript locally:
// String Manipulation Methods
const rawData = " [email protected] ";
const cleanEmail = rawData.trim();
const [username, domain] = cleanEmail.split("@");
console.log("Clean Email:", cleanEmail);
console.log("Username: ", username);
console.log("Domain: ", domain);
// String searching and replacement
const sentence = "JavaScript is great. JavaScript is flexible.";
const updated = sentence.replaceAll("JavaScript", "TypeScript");
console.log("Updated: ", updated);Expected Output:
Clean Email: [email protected] Username: john.doe Domain: enterprise.com Updated: TypeScript is great. TypeScript is flexible.
How It Works: Step-by-Step
- Lines 2-4: trim() removes whitespace and split("@") divides into username and domain.
- Lines 11-12: replaceAll replaces all occurrences without requiring global regex /g.
Key Concepts
- Strings in JavaScript are immutable primitives; methods always return a new string.
- replaceAll replaces all matches, while replace only updates the first match unless regex /g is used.
- includes(), startsWith(), and endsWith() provide readable boolean checks.
Common Mistake: Expecting str.replace() to replace all occurrences by default
str.replace("a", "b") only replaces the first instance. Use replaceAll() or /a/g.
❌ Incorrect
"cat and cat".replace("cat", "dog") // "dog and cat"✅ Correct
"cat and cat".replaceAll("cat", "dog") // "dog and dog"Related JavaScript Tutorials & Compiler
JavaScript Arrays: Methods (map, filter, reduce, slice)
Master modern array manipulation using push, pop, slice, map, filter, and reduce.
JavaScript Console I/O: Logging, Tables, and Formatting
Master console output with console.log, console.table, and standard process streams.
JavaScript Variables: let, const, and var Explained
Learn how to declare variables in modern JavaScript using let, const, and var with block scoping.
JavaScript Online Compiler
Open in Compilra IDE
Run and test JavaScript on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.