2.8 Module 2 · Variables, Data Types & Functions

String Operations

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.

1

Definition

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.

2

Simple Way

Strings are just text, and string operations help you work with that text:

.length Measure the text — how many characters does it contain?
.slice() Cut a portion out — extract characters between two positions
.replace() Swap one word or pattern for another — non-destructive
`${}` Template literals — embed variables directly into strings with backticks
3

Code Examples

Example 1 — .length
let text = "JavaScript";

console.log(text.length);        // 10 characters
console.log("Hello".length);     // 5
console.log("".length);          // 0 — empty string
Output
Click ▶ Run to execute
Explanation
  • length is a property (not a method) — no parentheses needed
  • It counts every character including spaces and punctuation
  • Useful for validation — e.g. checking a password meets a minimum length
Example 2 — .slice()
let 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
Output
Click ▶ Run to execute
Explanation
  • slice(start, end) extracts from start up to but not including end
  • Omitting end extracts from start all the way to the end of the string
  • Negative indices count backwards from the end — -6 means "start 6 from the end"
Example 3 — .replace()
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"
Output
Click ▶ Run to execute
Explanation
  • replace() returns a new string — the original is never modified (strings are immutable)
  • It only replaces the first occurrence of the search term
  • To replace all occurrences use replaceAll() or a regex with the g flag
Example 4 — Template Literals
let 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}.`);
Output
Click ▶ Run to execute
Explanation
  • Template literals use backticks (` `), not quotes
  • ${} embeds any JavaScript expression directly inside the string
  • Much cleaner than string concatenation with + — especially for long sentences
Example 5 — More Useful String Methods
let 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
Output
Click ▶ Run to execute
Explanation
  • toUpperCase() / toLowerCase() — change the case of every character
  • trim() — removes whitespace from both ends, essential when handling form input
  • includes() — returns true/false, great for search/filter logic
  • indexOf() — returns the starting position of a substring, or -1 if not found
4

Real-Life Example

Think of a text editor like WhatsApp — every feature maps to a string method:

.length
The character counter below a message box — "42 / 160"
.slice()
Selecting and copying part of a message to quote it
.replace()
Find & Replace in a document — swap one word for another
`${}`
A notification template — "Hello Aman, your order is ready!"
.trim()
Auto-removing accidental spaces the user typed before or after
.includes()
The search bar — does this message contain your keyword?
5

HTML + JavaScript Example

Click ▶ Preview, type your name, and watch multiple string methods run on your input simultaneously — all at once on a real page.

Live in Browser — String Methods on Your Input
<!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>
Live Preview
6

Tasks (Practice)

Easy Task 1 — String length & case
Starter code
let message = "Hello JavaScript";
  • Print the length of message
  • Print it in all uppercase and all lowercase
  • Use a template literal to print: "The message has X characters"
Medium Task 2 — Find and replace
Starter code
let sentence = "I love Python";
  • Replace "Python" with "JavaScript" using replace()
  • Print both the original and the new string to confirm the original is unchanged
  • Use includes() to check if the new string contains "JavaScript"
7

MCQs

Q1
What is the output?
let str = "Hello";
console.log(str.length);
Output
Run it to verify
  • A 4
  • B 5
  • C 6
  • D Error
💡 B is correct. "Hello" contains exactly 5 characters: H-e-l-l-o. length counts every character including spaces — none here.
Q2
What does slice() do?
let text = "JavaScript";
console.log(text.slice(0, 4));
Output
Run it to verify
  • A Deletes part of the string
  • B Extracts part of the string
  • C Replaces part of the string
  • D Converts the string to an array
💡 B is correct. 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.
Q3
Which syntax correctly uses a template literal?
let name = "Aman";

// Which one outputs: "Hello Aman" ?
console.log(`Hello ${name}`);
Output
Run it to verify
  • A "Hello ${name}"
  • B 'Hello ${name}'
  • C `Hello ${name}`
  • D Hello ${name}
💡 C is correct. Template literals must use backticks (` `). Inside double or single quotes, ${name} is treated as literal text — not evaluated as a variable.
8

Pro Tips & Extra Knowledge

  • 01

    Strings are immutable — every string method returns a new string. The original is never changed. Always store the result in a variable:

    Strings are immutable
    let original = "hello";
    let upper    = original.toUpperCase();
    
    console.log(original); // "hello"  — unchanged
    console.log(upper);    // "HELLO"  — new string returned
    Output
    Click ▶ Run to execute
  • 02

    Always trim() user input before processing it — leading or trailing spaces silently break comparisons and length checks:

    Trim before using input
    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
    Output
    Click ▶ Run to execute
  • 03

    Use replaceAll() when you need to replace every occurrence — replace() only handles the first match:

    replace() vs replaceAll()
    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"
    Output
    Click ▶ Run to execute
  • 04

    Prefer template literals over + concatenation — they are easier to read, support multi-line strings, and allow any expression inside ${}:

    Template literals vs concatenation
    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}`);
    Output
    Click ▶ Run to execute
Mini Challenge

Two operations on the same string — predict each output before running. Pay attention to indices.

What does this print?
let str = "JavaScript";

console.log(str.slice(4));
console.log(str.replace("Script", "Code"));
Output
Think first, then run!
Step-by-Step Explanation
// 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.