JavaScript Strings Interview Questions and Answers
Explore string creation, immutability, common operations, and safe ways to inspect or transform text.
Frequently Asked Questions
Important questions are highlighted in the sections below; select one to jump to its answer.
- Difference between padStart and padEnd functions?
- Difference between search and match functions?
- What is a string in JavaScript?
- What is the string length property?
- Difference between string literal and string template literal?
- Difference between indexOf and includes?
- Difference between indexOf and lastIndexOf?
Theoretical JavaScript Interview Questions
A string is just text - a sequence of characters. In JavaScript, strings are primitive and immutable, meaning operations like replace() or toUpperCase() don't modify the original string, they return a new one. You can quote them with single quotes, double quotes, or backticks - in modern code, backticks (template literals) are usually the best choice since they support interpolation and multiline without extra syntax.
Always use === for string comparisons. With ==, JavaScript tries to coerce types before comparing - so "123" == 123 is true, which is almost never what you want. With ===, both value and type must match. This is one of the most common sources of subtle bugs, so just make === your default.
"123" == 123 // true (string is converted to a number)
=== (strict equality) checks for both value and type equality without type conversion - use this one.
"123" === 123 //false
All three extract a portion of a string, but slice() is the one you'll reach for most. It supports negative indices (counting from the end) and has consistent, predictable behavior:
- slice:
- substring:
-
substr:
//substr(start, length) (deprecated but still used) let str = "Hello, world!"; let part = str.substr(0, 5); // "Hello"
//slice(start, end)
let str = "Hello, world!";
let part = str.slice(0, 5); // "Hello"
//substring(start, end)
let str = "Hello, world!";
let part = str.substring(0, 5); // "Hello"
In practice, just use slice() - it works like substring() but also accepts negative indices, which makes it more flexible. substring() is fine but older. substr() is deprecated - it takes a start index and a length rather than start and end, which is confusing, so drop it from your vocabulary:
slice(start, end) - supports negative indices, the go-to choice:
- Extracts from start to end (not inclusive).
- Accepts negative indices.
"Hello".slice(1, 4); // "ell"
"Hello".slice(-4, -1); // "ell"
substring(start, end): -
- Extracts from start to end (not inclusive).
- Does not accept negative indices.
"Hello".substring(1, 4); // "ell"
substr(start, length) (deprecated):
- Extracts a substring starting at start with a specified length.
- Accepts negative start values.
"Hello".substr(1, 3); // "ell"
"Hello".substr(-4, 3); // "ell"
Template literals (backticks) are the modern way to work with strings in JavaScript. They let you embed expressions directly with ${} and span multiple lines without escape characters. In modern code, reach for backticks by default - they're strictly more capable than single or double quoted strings.
String Interpolation: Embed variables or expressions using ${}.
let name = "John";
let greeting = `Hello, ${name}!`; // "Hello, John!"
Multi-line strings: Write strings over multiple lines without needing escape characters.
let multiLine = `This is a multi-line string.`;
Differences from regular strings:
- Template literals: Use backticks (` `), support interpolation, and handle multi-line easily.
- Regular strings: Use single (' ') or double (" ") quotes and require manual concatenation for variables or expressions.
replace(): - Replaces only the first occurrence of a substring or pattern.
let str = "apple apple";
str.replace("apple", "orange"); // "orange apple"
replaceAll(): - Replaces all occurrences of a substring or pattern.
let str = "apple apple";
str.replaceAll("apple", "orange"); //"orange orange"
The big gotcha: replace() with a string pattern only replaces the first match. For all occurrences, use replaceAll() or pass a regex with the g flag to replace(). replaceAll() was added in ES2021 as the more readable option.
JavaScript strings are internally encoded as UTF-16. Most characters you'll deal with are in the Basic Multilingual Plane (BMP) and take one 16-bit code unit, so str.length equals the number of characters. The catch is emojis and some special characters use two code units (a surrogate pair), so '??'.length is 2, not 1. Use for...of to iterate by actual characters rather than raw code units.
1. Unicode: Unicode is a character encoding standard that aims to represent every character from every writing system. Each character is assigned a unique code point (e.g., 'A' = U+0041). JavaScript strings are based on the Unicode standard, meaning they can represent characters from virtually any language.
2. UTF-16: UTF-16 (16-bit Unicode Transformation Format) is the encoding JavaScript uses internally to represent strings. Each character is represented by 16 bits (2 bytes). For characters beyond the Basic Multilingual Plane (BMP), UTF-16 uses two 16-bit code units (known as a surrogate pair). Examples:
- A character like 'A' is represented as a single 16-bit code unit.
- Emojis or certain special characters (e.g., ??) require two 16-bit units in UTF-16.
let str = '??';
console.log(str.length); // 2 (because it uses a surrogate pair in UTF-16)
The for...of loop is the preferred way - it correctly handles multi-byte characters (like emojis) by iterating over code points rather than raw code units. A regular for loop or split('') can split surrogate pairs, giving you garbled results with emoji. Here are the main options:
1. for loop:
let str = "Hello";
for (let i = 0; i < str.length; i++) {
console.log(str[i]);
}
2. for...of` loop (preferred for strings):
let str = "Hello";
for (let char of str) {
console.log(char);
}
3. split() method with forEach():
let str = "Hello";
str.split('').forEach(char => console.log(char));
4. charAt() method in a loop:
let str = "Hello";
for (let i = 0; i < str.length; i++) {
console.log(str.charAt(i));
}
charAt(i) returns the character at index i as a string, while charCodeAt(i) returns its numeric Unicode value. In most modern code you'll see bracket notation (str[i]) instead of charAt() - they're equivalent except for out-of-bounds: charAt() returns '' while str[i] returns undefined. Know that difference and you'll be fine with either.
1. charAt(index): Returns the character at the specified index in the string. - Output is a string.
let str = "Hello";
str.charAt(1); // "e"
2. charCodeAt(index): Returns the Unicode character code (numeric value) of the character at the specified index. - Output is a number.
let str = "Hello";
str.charCodeAt(1); // 101 (Unicode code for "e")
In short, charAt() gives you the character, while charCodeAt() gives you its numeric Unicode value.
The behavior differs depending on how you access it: charAt(outOfBounds) returns an empty string '', while bracket notation str[outOfBounds] returns undefined. Both handle it gracefully without throwing. In practice this distinction rarely matters, but if you're doing something like if (str.charAt(i) === '') to check for missing characters, that's the reason why:
1. Using charAt: Returns an empty string ("").
let str = "Hello";
console.log(str.charAt(10)); // ""
2. Using bracket notation ([]): Returns undefined.
let str = "Hello";
console.log(str[10]); // undefined
Both cases handle out-of-range indices gracefully without throwing an error - charAt returns '' and bracket notation returns undefined.
Yes, strings are immutable in JavaScript - you can't change a character in place. Assigning to str[0] silently does nothing. Every string method that looks like it modifies the string (like replace(), toUpperCase(), trim()) actually returns a new string. This is generally fine, but be aware that creating many intermediate strings in hot loops can hurt performance.
let str = "Hello";
str[0] = "h"; // This has no effect, strings are immutable
console.log(str); // "Hello"
To change a string, you need to create a new one - for example:
let newStr = str.replace("H", "h"); // "hello"
Template literals are the way to go for multi-line strings - just put line breaks directly in the backtick string. The old approach of using \n in a regular string still works but is harder to read. If you're building multi-line strings dynamically, pushing parts into an array and calling .join('\n') is a clean pattern.
1. Using Template Literals (best option): Template literals, enclosed in backticks (` `), allow you to create multi-line strings easily.
let multiLine = `This is
a multi-line
string.`;
2. Using Escape Character (\n): You can also use \n for new lines within regular strings.
let multiLine = "This is\na multi-line\nstring.";
A tagged template literal lets you preprocess a template literal with a function. The tag function receives the string parts as an array and the interpolated values as separate arguments - letting you produce something other than a plain concatenated string. This is how libraries like styled-components, GraphQL's gql, and SQL query builders work. It's an advanced feature you probably won't write yourself often, but you'll encounter it in third-party code.
//Syntax:
tagFunction`Template literal string ${expression}`;
//Example:
function myTag(strings, ...values) {
console.log(strings); // Array of string parts
console.log(values); // Array of expression values
return strings[0] + values[0]; // Just for demonstration
}
let name = "John";
let result = myTag`Hello, ${name}!`;
console.log(result); // "Hello, John!"
myTag is the tag function that receives:
- strings: an array of string segments (static parts of the template).
- values: the values of the interpolated expressions.
You can process these values and return a new string or value. Common use cases:
- Custom string formatting (e.g., currency, localization).
- Security (e.g., escaping HTML or SQL injection prevention).
- More complex processing of template literals beyond simple interpolation.
.length tells you how many UTF-16 code units a string contains. For most everyday text it equals the number of characters, but emoji and some Unicode characters take two code units each, so '😀'.length is 2, not 1. It's read-only - trying to assign to it does nothing. For counting visible characters with emoji, use the spread operator: [...str].length.
Template literals (backticks) replaced the old string concat dance. With `Hello, ${name}!` you can embed any expression directly instead of using +. They also preserve actual line breaks, making multi-line strings trivial. Prefer template literals whenever you're building strings with dynamic content - the code is cleaner and much easier to read.
padStart() pads from the left, padEnd() from the right - both until the string hits the target length. The classic use case for padStart is zero-padding numbers: '5'.padStart(3, '0') gives '005'. Useful for formatting IDs, timestamps, or aligned table columns. If the string is already at or longer than the target length, nothing happens.
Use includes() when you just need to know if something is there - it returns a clear true/false and reads like plain English. Use indexOf() when you also need the position. A common mistake is writing if (str.indexOf('x')) which is truthy even when the result is 0 (found at the start) - includes() avoids that trap entirely.
indexOf() scans left to right and returns the first match, lastIndexOf() scans right to left and returns the last. Both return -1 if nothing is found. A practical use: getting just the filename from a path - path.lastIndexOf('/') finds the final slash so you can slice from there. Both methods work on strings and arrays.
search() takes a regex and returns the index of the first match (or -1) - it's basically indexOf() but with regex support. match() returns the actual matched strings as an array, or null if nothing matched. Use match() with the g flag to collect all occurrences. Also consider matchAll() for a more ergonomic way to get all matches with capture groups.
No. String values are immutable; operations such as `slice()` or `replace()` return a new string instead of changing the original. A variable holding a string can still be reassigned.
`length` counts UTF-16 code units, not user-perceived characters or Unicode code points. A supplementary character can occupy two code units, and a grapheme such as an emoji sequence can contain multiple code points.
`localeCompare()` compares strings according to locale-sensitive collation rules and can accept locale and options for sorting. Its result should be treated by sign: negative, zero, or positive-not as a particular exact number.
JavaScript Practical and Coding Interview Questions
Problem: Store a person's name and create a greeting that includes the name using a template literal.
const name = 'Ada';
const greeting = `Hello, ${name}!`;
console.log(greeting);Problem: Convert the numeric quantity 5 to a string and use it in a message.
const quantity = 5;
const message = 'Quantity: ' + String(quantity);
console.log(message);Problem: Write a function that parses a decimal string and returns null when the result is not finite.
function parseAmount(value) {
const amount = Number(value);
return Number.isFinite(amount) ? amount : null;
}
console.log(parseAmount('19.95'));
console.log(parseAmount('19.95 USD'));Problem: Write a function that checks for a substring without being affected by letter case.
function containsIgnoreCase(text, query) {
return text.toLowerCase().includes(query.toLowerCase());
}
console.log(containsIgnoreCase('JavaScript Guide', 'SCRIPT'));Problem: Return the index of the first occurrence of 'cat' in the sample string.
const sentence = 'A cat, then another cat.';
console.log(sentence.indexOf('cat'));Problem: Use a global regular expression to collect every whole-word occurrence of 'cat'.
const sentence = 'cat scatter catapult cat';
const matches = sentence.match(/\bcat\b/g) || [];
console.log(matches.length, matches);Problem: Read the code point of an emoji and convert that number back into a string.
const character = '🙂';
const codePoint = character.codePointAt(0);
console.log(codePoint, String.fromCodePoint(codePoint));Problem: Write a function that treats an empty string and whitespace-only strings as blank.
function isBlank(value) {
return value.trim().length === 0;
}
console.log(isBlank(''));
console.log(isBlank(' '));
console.log(isBlank('JavaScript'));Problem: Write a function that reverses a string by Unicode code point using iteration, then print the reversed result for a string that includes a supplementary character. (This does not need to preserve multi-code-point grapheme clusters.)
function reverseByCodePoint(text) {
return Array.from(text).reverse().join("");
}
console.log(reverseByCodePoint("A🙂B"));Problem: Write a function that checks whether a label is a palindrome after ignoring spaces, punctuation, and letter case. Use the same input string for normalization and comparison.
function isPalindrome(label) {
const normalized = label.toLowerCase().replace(/[^a-z0-9]/g, '');
let left = 0;
let right = normalized.length - 1;
while (left < right) {
if (normalized[left] !== normalized[right]) return false;
left += 1;
right -= 1;
}
return true;
}
console.log(isPalindrome('Civic 7 civic'));
console.log(isPalindrome('Market 42'));Problem: Write a function that returns whether two phrases use the same letters with the same counts. Ignore spaces and case, and use only English letters in this example.
function areAnagrams(first, second) {
const normalize = (value) => value.toLowerCase().replace(/[^a-z]/g, '');
const left = normalize(first);
const right = normalize(second);
if (left.length !== right.length) return false;
const counts = new Map();
for (const letter of left) counts.set(letter, (counts.get(letter) || 0) + 1);
for (const letter of right) {
const count = counts.get(letter) || 0;
if (count === 0) return false;
counts.set(letter, count - 1);
}
return true;
}
console.log(areAnagrams('dusty', 'study'));
console.log(areAnagrams('dusty', 'study hall'));Problem: Create a function that trims a heading, collapses repeated whitespace, and capitalizes each word while making its remaining letters lowercase.
function titleCase(heading) {
return heading
.trim()
.split(/\s+/)
.filter(Boolean)
.map((word) => word[0].toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
}
console.log(titleCase(' trail map for JUNE '));Problem: Return the first longest word in a whitespace-separated note. Return an empty string when the note has no words.
function longestWord(note) {
const words = note.trim().split(/\s+/).filter(Boolean);
return words.reduce((longest, word) =>
word.length > longest.length ? word : longest, '');
}
console.log(longestWord('quiet paths need clear markers'));Problem: Write a function that removes repeated Unicode characters from a string while keeping the original order of their first appearances.
function uniqueCharacters(value) {
const seen = new Set();
let result = '';
for (const character of value) {
if (!seen.has(character)) {
seen.add(character);
result += character;
}
}
return result;
}
console.log(uniqueCharacters('maplemoon'));Problem: Use a stack to check matching parentheses, square brackets, and curly braces. Ignore other characters and reject a closing bracket that does not match the latest opening bracket.
function hasBalancedBrackets(expression) {
const expectedOpening = { ')': '(', ']': '[', '}': '{' };
const opening = new Set(Object.values(expectedOpening));
const stack = [];
for (const character of expression) {
if (opening.has(character)) {
stack.push(character);
} else if (Object.hasOwn(expectedOpening, character)) {
if (stack.pop() !== expectedOpening[character]) return false;
}
}
return stack.length === 0;
}
console.log(hasBalancedBrackets('cart[items[0] + (tax * 2)]'));
console.log(hasBalancedBrackets('cart[(items[0])}'));