Chapter 10 Intermediate 55 Questions

Practice Questions — Strings and Template Literals

← Back to Notes
11 Easy
13 Medium
9 Hard

Topic-Specific Questions

Question 1
Easy
What is the output of the following code?
const name = "Aarav";
console.log(name.length);
console.log(name[0]);
length counts characters. Index 0 is the first character.
5
A
Question 2
Easy
What is the output?
const str = "Hello World";
console.log(str.toUpperCase());
console.log(str);
toUpperCase returns a new string. The original is unchanged.
HELLO WORLD
Hello World
Question 3
Easy
What is the output?
const text = "JavaScript";
console.log(text.includes("Script"));
console.log(text.includes("script"));
includes is case-sensitive.
true
false
Question 4
Easy
What is the output?
const name = "Priya";
const age = 15;
console.log(`${name} is ${age} years old.`);
Template literals use ${} for interpolation.
Priya is 15 years old.
Question 5
Easy
What is the output?
const str = "Hello, World!";
console.log(str.indexOf("World"));
console.log(str.indexOf("world"));
indexOf returns -1 if not found. It is case-sensitive.
7
-1
Question 6
Easy
What is the output?
console.log("Ha".repeat(4));
repeat(n) repeats the string n times.
HaHaHaHa
Question 7
Medium
What is the output?
const text = "JavaScript";
console.log(text.slice(4, 10));
console.log(text.slice(-6));
slice(4, 10) extracts from index 4 to 9. Negative index counts from the end.
Script
Script
Question 8
Medium
What is the output?
const csv = "Aarav,Priya,Rohan";
const names = csv.split(",");
console.log(names);
console.log(names.join(" - "));
split breaks at commas. join combines with the given separator.
["Aarav", "Priya", "Rohan"]
Aarav - Priya - Rohan
Question 9
Medium
What is the output?
const str = "   hello   ";
console.log(str.trim());
console.log(str.trim().length);
trim removes whitespace from both ends.
hello
5
Question 10
Medium
What is the output?
const text = "hello hello hello";
console.log(text.replace("hello", "hi"));
console.log(text.replaceAll("hello", "hi"));
replace changes only the first match. replaceAll changes all.
hi hello hello
hi hi hi
Question 11
Medium
What is the output?
const n = 42;
console.log(String(n).padStart(6, "0"));
console.log("Hi".padEnd(10, "."));
padStart pads the beginning. padEnd pads the end.
000042
Hi........
Question 12
Medium
What is the output?
const score = 85;
console.log(`Grade: ${score >= 90 ? "A" : score >= 75 ? "B" : "C"}`);
Ternary operators work inside ${}.
Grade: B
Question 13
Hard
What is the output?
const str = "abcabc";
console.log(str.indexOf("c"));
console.log(str.lastIndexOf("c"));
console.log(str.indexOf("c", 3));
indexOf searches from the start. lastIndexOf from the end. The second argument is the start position.
2
5
5
Question 14
Hard
What is the output?
const students = ["Aarav", "Priya", "Rohan"];
const html = students.map(s => `
  • ${s}
  • `).join("\n"); console.log(html);
    map transforms each name into an li element. join combines with newlines.
    <li>Aarav</li>
    <li>Priya</li>
    <li>Rohan</li>
    Question 15
    Hard
    What is the output?
    const email = "priya.sharma@school.edu.in";
    const parts = email.split(".");
    console.log(parts);
    console.log(parts.length);
    split at every dot character.
    ["priya", "sharma@school", "edu", "in"]
    4
    Question 16
    Easy
    What is the difference between single quotes, double quotes, and backticks in JavaScript?
    Two of them are the same. One has special powers.
    Single quotes (') and double quotes (") are functionally identical - use either one consistently. Backticks (`) create template literals which have special features: string interpolation with ${expression}, multiline strings (actual line breaks preserved), and tagged templates. Use backticks whenever you need variables in a string or multiline text.
    Question 17
    Medium
    Why are strings called immutable in JavaScript? What does that mean practically?
    You cannot change a string after it is created.
    Immutable means strings cannot be changed once created. You cannot modify individual characters: str[0] = "X" does nothing. Every string method (toUpperCase, replace, slice, etc.) returns a new string instead of modifying the original. To change a string variable, you must reassign it to a new string.
    Question 18
    Hard
    What is the output?
    const words = "  hello   world  ";
    const clean = words.trim().split(/\s+/);
    console.log(clean);
    console.log(clean.join("-"));
    trim first, then split on one or more whitespace characters.
    ["hello", "world"]
    hello-world
    Question 19
    Easy
    What is the output?
    const str = "Hello";
    console.log(str.startsWith("He"));
    console.log(str.endsWith("lo"));
    console.log(str.startsWith("he"));
    Both methods are case-sensitive.
    true
    true
    false
    Question 20
    Hard
    What is the output?
    const student = { name: "Diya", score: 95 };
    const card = `

    ${student.name}

    ${student.score >= 90 ? "Distinction" : "Pass"}

    `; console.log(card);
    Template literal with nested ternary and multiline HTML.
    <div>
    <h3>Diya</h3>
    <p>Distinction</p>
    </div>

    Mixed & Application Questions

    Question 1
    Easy
    What is the output?
    const word = "Code";
    console.log(word.split(""));
    split with empty string splits into individual characters.
    ["C", "o", "d", "e"]
    Question 2
    Easy
    What is the output?
    console.log("5".padStart(3, "0"));
    console.log("42".padStart(3, "0"));
    console.log("123".padStart(3, "0"));
    padStart pads to the target length. If already long enough, no padding is added.
    005
    042
    123
    Question 3
    Medium
    What is the output?
    const email = "aarav@school.com";
    const username = email.slice(0, email.indexOf("@"));
    const domain = email.slice(email.indexOf("@") + 1);
    console.log(username);
    console.log(domain);
    Find the @ position, then slice before and after it.
    aarav
    school.com
    Question 4
    Medium
    What is the output?
    const str = "JavaScript";
    console.log(str.charAt(0) + str.slice(1).toLowerCase());
    Take the first character, then lowercase the rest.
    Javascript
    Question 5
    Medium
    What is the output?
    const arr = ["Maths", "Science", "English"];
    const result = arr.map(s => s.toUpperCase()).join(", ");
    console.log(result);
    Map to uppercase, then join with comma-space.
    MATHS, SCIENCE, ENGLISH
    Question 6
    Medium
    What is the output?
    const str = "hello world hello";
    const count = str.split("hello").length - 1;
    console.log(count);
    split at "hello" creates one more segment than there are occurrences.
    2
    Question 7
    Hard
    What is the output?
    const words = ["the", "quick", "brown", "fox"];
    const result = words
      .map(w => w.charAt(0).toUpperCase() + w.slice(1))
      .join(" ");
    console.log(result);
    Capitalize the first letter of each word.
    The Quick Brown Fox
    Question 8
    Hard
    What is the output?
    const str = "racecar";
    const reversed = str.split("").reverse().join("");
    console.log(reversed);
    console.log(str === reversed);
    Split into chars, reverse the array, join back. Is racecar a palindrome?
    racecar
    true
    Question 9
    Hard
    What is the output?
    const data = [
      { name: "Aarav", score: 92 },
      { name: "Priya", score: 88 }
    ];
    
    const html = data.map(s => 
      `${s.name}${s.score}`
    ).join("\n");
    
    console.log(`\n${html}\n
    `);
    Build table rows from data, then wrap in a table element.
    <table>
    <tr><td>Aarav</td><td>92</td></tr>
    <tr><td>Priya</td><td>88</td></tr>
    </table>
    Question 10
    Hard
    What is the output?
    console.log(String.raw`Hello\nWorld`);
    console.log(`Hello\nWorld`);
    String.raw does not process escape sequences.
    Hello\nWorld
    Hello
    World
    Question 11
    Medium
    What is the difference between split and join? How do they work together?
    One breaks strings into arrays. The other combines arrays into strings.
    split(separator) breaks a string into an array at each occurrence of the separator. join(separator) combines array elements into a string with the separator between each element. They are inverses of each other. "a-b-c".split("-") gives ["a","b","c"]. ["a","b","c"].join("-") gives "a-b-c".
    Question 12
    Easy
    What is the output?
    const a = 10;
    const b = 20;
    console.log(`Sum: ${a + b}`);
    console.log(`Product: ${a * b}`);
    Any expression works inside ${}.
    Sum: 30
    Product: 200
    Question 13
    Medium
    What is the output?
    const str = "abcdef";
    console.log(str.slice(2, 5));
    console.log(str.slice(-3));
    console.log(str.slice(1, -1));
    Negative indices count from the end. End index is exclusive.
    cde
    def
    bcde

    Multiple Choice Questions

    MCQ 1
    What does str.length return?
    • A. The last index of the string
    • B. The number of characters in the string
    • C. The number of words in the string
    • D. The size in bytes
    Answer: B
    B is correct. length returns the total number of characters. The last index is length - 1 (option A). It counts characters, not words (option C).
    MCQ 2
    Which method checks if a string contains a specific substring?
    • A. has()
    • B. contains()
    • C. includes()
    • D. find()
    Answer: C
    C is correct. includes() returns true or false depending on whether the substring is found. has() and contains() are not string methods. find() is an array method.
    MCQ 3
    What is the output of "Hello".indexOf("xyz")?
    • A. 0
    • B. false
    • C. -1
    • D. undefined
    Answer: C
    C is correct. indexOf returns -1 when the substring is not found. It returns a number, not a boolean (option B) or undefined (option D).
    MCQ 4
    Which of these creates a template literal?
    • A. "Hello ${name}"
    • B. 'Hello ${name}'
    • C. `Hello ${name}`
    • D. (Hello ${name})
    Answer: C
    C is correct. Template literals use backticks (`). Single and double quotes (options A, B) treat ${name} as literal text. Option D is not valid syntax.
    MCQ 5
    What does trim() do?
    • A. Removes all spaces from the string
    • B. Removes spaces from the beginning and end
    • C. Removes the first and last characters
    • D. Shortens the string to 10 characters
    Answer: B
    B is correct. trim() removes whitespace from both ends of a string. It does NOT remove spaces in the middle (option A) or remove non-whitespace characters (option C).
    MCQ 6
    What is the difference between replace and replaceAll?
    • A. replace is faster than replaceAll
    • B. replace changes the first match, replaceAll changes all matches
    • C. replace changes all matches, replaceAll changes the first
    • D. There is no difference
    Answer: B
    B is correct. replace() only replaces the first occurrence of the search string. replaceAll() replaces every occurrence. Both return new strings.
    MCQ 7
    What does "Hello".split("") return?
    • A. ["Hello"]
    • B. ["H", "e", "l", "l", "o"]
    • C. "Hello"
    • D. 5
    Answer: B
    B is correct. split("") with an empty string splits at every character boundary, creating an array of individual characters: ["H", "e", "l", "l", "o"].
    MCQ 8
    What is the end index parameter in slice(start, end)?
    • A. The number of characters to extract
    • B. The last index to include
    • C. The first index to exclude
    • D. The total length of the result
    Answer: C
    C is correct. In slice(start, end), the character at the end index is NOT included. It extracts from start up to (but not including) end. "Hello".slice(1, 4) gives "ell" (indices 1, 2, 3).
    MCQ 9
    Why are strings called immutable in JavaScript?
    • A. You cannot assign them to variables
    • B. They cannot be compared
    • C. They cannot be changed after creation
    • D. They can only be used with const
    Answer: C
    C is correct. Immutable means strings cannot be modified after creation. You cannot change individual characters. Every string method returns a new string. The variable can be reassigned, but the string itself cannot be altered.
    MCQ 10
    What does ${ } do inside a template literal?
    • A. Creates a new variable
    • B. Embeds a JavaScript expression whose result is inserted into the string
    • C. Adds a comment
    • D. Escapes special characters
    Answer: B
    B is correct. ${expression} evaluates the JavaScript expression inside and inserts the result into the string. This is called string interpolation. Any valid expression works: variables, math, function calls, ternary operators.
    MCQ 11
    What is the output of "abc".padStart(2, "0")?
    • A. "0abc"
    • B. "abc"
    • C. "00abc"
    • D. "ab"
    Answer: B
    B is correct. padStart(2, "0") pads to a total length of 2. Since "abc" is already 3 characters (longer than 2), no padding is added. The string is returned unchanged.
    MCQ 12
    What does String.raw do?
    • A. Removes all escape sequences from a string
    • B. Returns the string without processing escape sequences
    • C. Converts the string to raw bytes
    • D. Creates an unformatted string
    Answer: B
    B is correct. String.raw is a tagged template that returns the raw string content without processing escape sequences like \n or \t. Backslashes are treated as literal characters.
    MCQ 13
    What is a tagged template literal?
    • A. A template literal with HTML tags
    • B. A function that processes a template literal's parts
    • C. A template literal with a label
    • D. A template literal stored in a variable
    Answer: B
    B is correct. A tagged template is a function placed before a template literal: myTag`text ${value}`. The function receives the string parts and interpolated values separately, allowing custom processing.
    MCQ 14
    How do you check if a string is a palindrome?
    • A. str.isPalindrome()
    • B. str === str.reverse()
    • C. str === str.split("").reverse().join("")
    • D. str.palindrome()
    Answer: C
    C is correct. Strings do not have a reverse() method. You must split into an array, reverse the array, and join back into a string. If the result equals the original, it is a palindrome.

    Coding Challenges

    Challenge 1: Capitalize First Letter of Each Word

    Easy
    Aarav has the string "hello world from javascript". Write a function titleCase that capitalizes the first letter of each word.
    Sample Input
    "hello world from javascript"
    Sample Output
    Hello World From Javascript
    Use split, map, and join.
    function titleCase(str) {
      return str.split(" ")
        .map(word => word.charAt(0).toUpperCase() + word.slice(1))
        .join(" ");
    }
    
    console.log(titleCase("hello world from javascript"));

    Challenge 2: Count Character Frequency

    Easy
    Priya has the string "programming". Write a program that counts how many times each character appears.
    Sample Input
    "programming"
    Sample Output
    { p: 1, r: 2, o: 1, g: 2, a: 1, m: 2, i: 1, n: 1 }
    Use split and reduce.
    const str = "programming";
    const freq = str.split("").reduce((acc, char) => {
      acc[char] = (acc[char] || 0) + 1;
      return acc;
    }, {});
    
    console.log(freq);

    Challenge 3: Generate an HTML Card from a Student Object

    Medium
    Use template literals to generate an HTML card from the student object: {name: "Kavya", grade: "10th", score: 94, subjects: ["Maths", "Science", "English"]}. The card should include the name, grade, score with a status (Distinction if >= 90, else Pass), and a list of subjects.
    Sample Input
    (No input required)
    Sample Output
    (An HTML card with student details and a subject list)
    Use template literals with ${} interpolation. Use map and join for the subjects list.
    const student = {
      name: "Kavya",
      grade: "10th",
      score: 94,
      subjects: ["Maths", "Science", "English"]
    };
    
    const card = `<div class="student-card">
      <h3>${student.name}</h3>
      <p>Grade: ${student.grade} | Score: ${student.score}/100</p>
      <p>Status: ${student.score >= 90 ? "Distinction" : "Pass"}</p>
      <h4>Subjects:</h4>
      <ul>
        ${student.subjects.map(s => `<li>${s}</li>`).join("\n    ")}
      </ul>
    </div>`;
    
    console.log(card);

    Challenge 4: Palindrome Checker

    Medium
    Rohan wants to check if a string is a palindrome (reads the same forwards and backwards). Write a function isPalindrome that ignores spaces and case.
    Sample Input
    "Race Car"
    Sample Output
    true
    Convert to lowercase and remove spaces before checking.
    function isPalindrome(str) {
      const clean = str.toLowerCase().replaceAll(" ", "");
      const reversed = clean.split("").reverse().join("");
      return clean === reversed;
    }
    
    console.log(isPalindrome("Race Car"));   // true
    console.log(isPalindrome("Hello"));      // false
    console.log(isPalindrome("Was It A Car Or A Cat I Saw")); // true

    Challenge 5: Email Validator

    Medium
    Diya wants to validate email addresses. Write a function isValidEmail that checks if a string has exactly one @, at least one character before @, and at least one dot after @.
    Sample Input
    "diya@school.com"
    Sample Output
    true
    Use string methods like indexOf, includes, and slice. Do not use regex.
    function isValidEmail(email) {
      const trimmed = email.trim();
      const atIndex = trimmed.indexOf("@");
      
      if (atIndex < 1) return false; // nothing before @
      if (trimmed.lastIndexOf("@") !== atIndex) return false; // multiple @
      
      const domain = trimmed.slice(atIndex + 1);
      if (!domain.includes(".")) return false; // no dot in domain
      if (domain.startsWith(".") || domain.endsWith(".")) return false;
      
      return true;
    }
    
    console.log(isValidEmail("diya@school.com"));  // true
    console.log(isValidEmail("@school.com"));      // false
    console.log(isValidEmail("diya@school"));      // false
    console.log(isValidEmail("diya@@school.com")); // false

    Challenge 6: String Compression

    Hard
    Arjun wants to compress strings by counting consecutive characters. For example, "aaabbbccda" becomes "a3b3c2d1a1". Write a function compress(str).
    Sample Input
    "aaabbbccda"
    Sample Output
    a3b3c2d1a1
    Use a loop. Handle single characters and edge cases.
    function compress(str) {
      if (str.length === 0) return "";
      
      let result = "";
      let count = 1;
      
      for (let i = 1; i <= str.length; i++) {
        if (i < str.length && str[i] === str[i - 1]) {
          count++;
        } else {
          result += str[i - 1] + count;
          count = 1;
        }
      }
      
      return result;
    }
    
    console.log(compress("aaabbbccda"));  // a3b3c2d1a1
    console.log(compress("aabbcc"));      // a2b2c2
    console.log(compress("abcdef"));      // a1b1c1d1e1f1

    Challenge 7: Build a Formatted Table from Data

    Hard
    Meera has an array of student objects. Write a function that generates a formatted text table using padStart and padEnd for alignment.
    Sample Input
    [{name: "Aarav", maths: 95, science: 88}, {name: "Priya", maths: 78, science: 92}]
    Sample Output
    Name Maths Science -------------------------- Aarav 95 88 Priya 78 92
    Use padStart and padEnd for column alignment.
    const students = [
      { name: "Aarav", maths: 95, science: 88 },
      { name: "Priya", maths: 78, science: 92 },
      { name: "Rohan", maths: 85, science: 76 }
    ];
    
    const header = "Name".padEnd(12) + "Maths".padStart(8) + "Science".padStart(10);
    const separator = "-".repeat(30);
    const rows = students.map(s => 
      s.name.padEnd(12) + String(s.maths).padStart(8) + String(s.science).padStart(10)
    );
    
    console.log(header);
    console.log(separator);
    rows.forEach(row => console.log(row));

    Challenge 8: URL Slug Generator

    Hard
    Vikram wants to convert blog titles into URL-friendly slugs. Write a function slugify that converts "Hello World! This is Great" to "hello-world-this-is-great" by lowercasing, removing special characters, and replacing spaces with hyphens.
    Sample Input
    "Hello World! This is Great"
    Sample Output
    hello-world-this-is-great
    Use toLowerCase, replace/replaceAll, and trim. Handle multiple spaces.
    function slugify(title) {
      return title
        .toLowerCase()
        .trim()
        .replace(/[^a-z0-9\s-]/g, "")  // remove special chars
        .replace(/\s+/g, "-")           // spaces to hyphens
        .replace(/-+/g, "-")            // collapse multiple hyphens
        .replace(/^-|-$/g, "");          // trim hyphens
    }
    
    console.log(slugify("Hello World! This is Great"));
    console.log(slugify("  JavaScript: The Good Parts  "));
    console.log(slugify("10 Tips & Tricks for Coding!"));

    Need to Review the Concepts?

    Go back to the detailed notes for this chapter.

    Read Chapter Notes

    Want to learn web development with a live mentor?

    Explore our Frontend Masterclass