Learn how to measure, slice, replace, and format text using JavaScript's rich set of built-in string methods — and write cleaner code with template literals.
String operations in JavaScript refer to the manipulation and
handling of text data using built-in properties and methods such as
length, slice(), replace(),
toUpperCase(), and modern features like
template literals.
Strings are one of the most frequently used data types in any program — they hold names, messages, URLs, and more. Mastering string methods lets you transform and query text data with precision and minimal code.
Strings are just text, and string operations help you work with that text:
let text = "JavaScript";
console.log(text.length); // 10 characters
console.log("Hello".length); // 5
console.log("".length); // 0 — empty string
length is a property (not a method) — no parentheses neededlet text = "JavaScript";
console.log(text.slice(0, 4)); // "Java" → indices 0–3
console.log(text.slice(4)); // "Script" → from index 4 to end
console.log(text.slice(-6)); // "Script" → last 6 characters
slice(start, end) extracts from start up to but not including endend extracts from start all the way to the end of the string-6 means "start 6 from the end"let text = "Hello World";
let newText = text.replace("World", "Aman");
console.log(newText); // "Hello Aman"
console.log(text); // "Hello World" — original unchanged!
// replace() only changes the FIRST occurrence
let repeated = "cat and cat";
console.log(repeated.replace("cat", "dog")); // "dog and cat"
replace() returns a new string — the original is never modified (strings are immutable)replaceAll() or a regex with the g flaglet name = "Aman";
let age = 22;
// Old way — concatenation
console.log("My name is " + name + " and I am " + age + " years old.");
// Modern way — template literal with backticks
console.log(`My name is ${name} and I am ${age} years old.`);
// Expressions work inside ${}
console.log(`Next year I will be ${age + 1}.`);
` `), not quotes${} embeds any JavaScript expression directly inside the string+ — especially for long sentenceslet str = " Hello JavaScript ";
console.log(str.toUpperCase()); // ALL CAPS
console.log(str.toLowerCase()); // all lowercase
console.log(str.trim()); // removes leading/trailing spaces
console.log(str.trim().length); // length after trimming
console.log(str.includes("Java")); // true — does it contain this?
console.log(str.indexOf("Java")); // 8 — position of first match
toUpperCase() / toLowerCase() — change the case of every charactertrim() — removes whitespace from both ends, essential when handling form inputincludes() — returns true/false, great for search/filter logicindexOf() — returns the starting position of a substring, or -1 if not foundThink of a text editor like WhatsApp — every feature maps to a string method:
Click ▶ Preview, type your name, and watch multiple string methods run on your input simultaneously — all at once on a real page.
<!DOCTYPE html>
<html>
<head><title>String Operations</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa">
<h2>String Operations Demo</h2>
<input id="nameInput" type="text" placeholder="Enter your name"
style="padding:8px 12px;border:1px solid #ccc;border-radius:6px;
font-size:1rem;width:220px">
<button onclick="runOps()"
style="margin-left:8px;padding:8px 18px;background:#f7df1e;border:none;
border-radius:6px;cursor:pointer;font-weight:700;font-size:1rem">
Submit
</button>
<div id="output" style="margin-top:16px;line-height:2.4;font-size:0.95rem"></div>
<script>
function runOps() {
let raw = document.getElementById("nameInput").value;
let name = raw.trim();
if (!name) {
document.getElementById("output").innerHTML =
"<b style='color:red'>Please enter a name.</b>";
return;
}
document.getElementById("output").innerHTML =
`<b>Input (trimmed):</b> ${name}<br>` +
`<b>.length:</b> ${name.length}<br>` +
`<b>.toUpperCase():</b> ${name.toUpperCase()}<br>` +
`<b>.toLowerCase():</b> ${name.toLowerCase()}<br>` +
`<b>.slice(0, 3):</b> ${name.slice(0, 3)}<br>` +
`<b>Template literal:</b> Hello, ${name}! Welcome to JS Mastery.`;
}
</script>
</body>
</html>
let message = "Hello JavaScript";
messagelet sentence = "I love Python";
"Python" with "JavaScript" using replace()includes() to check if the new string contains "JavaScript"let str = "Hello";
console.log(str.length);
"Hello" contains exactly 5 characters: H-e-l-l-o. length counts every character including spaces — none here.
slice() do?
let text = "JavaScript";
console.log(text.slice(0, 4));
slice(0, 4) returns a new string with characters from index 0 up to (but not including) index 4 — giving "Java". The original string is untouched.
let name = "Aman";
// Which one outputs: "Hello Aman" ?
console.log(`Hello ${name}`);
` `). Inside double or single quotes, ${name} is treated as literal text — not evaluated as a variable.
Strings are immutable — every string method returns a new string. The original is never changed. Always store the result in a variable:
let original = "hello";
let upper = original.toUpperCase();
console.log(original); // "hello" — unchanged
console.log(upper); // "HELLO" — new string returned
Always trim() user input before processing it — leading or trailing spaces silently break comparisons and length checks:
let input = " Aman "; // spaces from user typing
console.log(input.length); // 8 — includes spaces!
console.log(input.trim().length); // 4 — correct length
console.log(input === "Aman"); // false — spaces break it
console.log(input.trim() === "Aman"); // true — safe comparison
Use replaceAll() when you need to replace every occurrence — replace() only handles the first match:
let text = "cat and cat and cat";
console.log(text.replace("cat", "dog")); // "dog and cat and cat"
console.log(text.replaceAll("cat", "dog")); // "dog and dog and dog"
Prefer template literals over + concatenation — they are easier to read, support multi-line strings, and allow any expression inside ${}:
let item = "Laptop";
let price = 45000;
let qty = 2;
// Old way — hard to read
console.log("Item: " + item + " | Price: ₹" + (price * qty));
// Modern way — clean and expressive
console.log(`Item: ${item} | Price: ₹${price * qty}`);
Two operations on the same string — predict each output before running. Pay attention to indices.
let str = "JavaScript";
console.log(str.slice(4));
console.log(str.replace("Script", "Code"));
// str = "JavaScript"
// J a v a S c r i p t
// 0 1 2 3 4 5 6 7 8 9 ← indices
// Line 1: str.slice(4)
// Starts at index 4, goes to the end
// Characters from index 4 onwards: S c r i p t = "Script"
// Output → "Script"
// Line 2: str.replace("Script", "Code")
// Finds "Script" in "JavaScript" → replaces with "Code"
// "Java" + "Code" = "JavaCode"
// Output → "JavaCode"
// Final output:
// "Script" ← slice(4) extracts from index 4 to end
// "JavaCode" ← replace() swaps the matched substring
// Note: str itself is still "JavaScript" after both operations —
// strings are immutable; methods return NEW strings.