JavaScript:JavaScript Strings: Template Literals, Regex, and Methods
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:

ParameterTypeDescription
split(delim)MethodDivides string into an ordered list of substrings.
trim()MethodRemoves leading and trailing whitespace.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler