Practice Questions — Strings and Template Literals
← Back to NotesTopic-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.
5AQuestion 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 WORLDHello WorldQuestion 3
Easy
What is the output?
const text = "JavaScript";
console.log(text.includes("Script"));
console.log(text.includes("script"));includes is case-sensitive.
truefalseQuestion 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-1Question 6
Easy
What is the output?
console.log("Ha".repeat(4));repeat(n) repeats the string n times.
HaHaHaHaQuestion 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.
ScriptScriptQuestion 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 - RohanQuestion 9
Medium
What is the output?
const str = " hello ";
console.log(str.trim());
console.log(str.trim().length);trim removes whitespace from both ends.
hello5Question 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 hellohi hi hiQuestion 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.
000042Hi........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: BQuestion 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.
255Question 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"]4Question 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-worldQuestion 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.
truetruefalseQuestion 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.
005042123Question 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.
aaravschool.comQuestion 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.
JavascriptQuestion 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, ENGLISHQuestion 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.
2Question 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 FoxQuestion 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?
racecartrueQuestion 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\nWorldHelloWorldQuestion 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: 30Product: 200Question 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.
cdedefbcdeMultiple Choice Questions
MCQ 1
What does str.length return?
Answer: B
B is correct.
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?
Answer: C
C is correct.
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")?
Answer: C
C is correct.
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?
Answer: C
C is correct. Template literals use backticks (
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?
Answer: B
B is correct.
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?
Answer: B
B is correct.
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?
Answer: B
B is correct.
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)?
Answer: C
C is correct. In
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?
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.
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?
Answer: B
B is correct.
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")?
Answer: B
B is correct.
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?
Answer: B
B is correct.
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?
Answer: B
B is correct. A tagged template is a function placed before a template literal:
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?
Answer: C
C is correct. Strings do not have a
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
EasyAarav 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
EasyPriya 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
MediumUse 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
MediumRohan 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")); // trueChallenge 5: Email Validator
MediumDiya 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")); // falseChallenge 6: String Compression
HardArjun 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")); // a1b1c1d1e1f1Challenge 7: Build a Formatted Table from Data
HardMeera 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
HardVikram 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 NotesWant to learn web development with a live mentor?
Explore our Frontend Masterclass