Top JavaScript String Interview Questions: DSA and Coding Challenges
Prepare for JavaScript interviews with these essential string-related coding questions. Learn key concepts, explore data structure and algorithm (DSA) challenges, and master string manipulation techniques for technical interviews.
Key Points about Strings in JavaScript:
- String Definition: In JavaScript, a string is a sequence of characters enclosed within single (
' '
), double (" "
), or backticks (` `
). - String Immutability: Strings in JavaScript are immutable, meaning once created, their content cannot be changed directly.
- String Methods: JavaScript provides many built-in methods for string manipulation, such as:
charAt()
,concat()
,includes()
charAt()
,concat()
,includes()
slice()
,substring()
,substr()
split()
,replace()
,replaceAll()
trim()
,toLowerCase()
,toUpperCase()
- Template Literals: Introduced in ES6, template literals allow embedding expressions within strings using
${expression}
and support multi-line strings. - Escape Sequences: Special characters can be used in strings with escape sequences (e.g.,
\n
for a new line,\'
for single quotes). - String Coercion: JavaScript automatically converts non-string data types to strings when necessary (e.g., during concatenation).
- Unicode and UTF-16: JavaScript strings are based on UTF-16 encoding, allowing support for Unicode characters.
- String Length: You can determine the length of a string using
.length
.
Important Interview Questions:
Q1: How can you find the length of a string in JavaScript?
Answer: Use the .length
property.
let str = "Hello, world!";
console.log(str.length); // Output: 13
Q2: How can you reverse a string in JavaScript?
Answer: You can convert the string to an array, reverse it, and join it back into a string.
let str = "hello";
let reversedStr = str.split('').reverse().join('');
console.log(reversedStr); // Output: "olleh"
Q3: What is the difference between slice()
, substring()
, and substr()
?
Answer:
slice(start, end)
: Extracts a part of the string fromstart
toend
(not includingend
). It supports negative indexes.substring(start, end)
: Similar toslice()
, but does not support negative indexes.substr(start, length)
: Extracts a substring starting fromstart
and continuing forlength
characters.
let str = "hello";
let reversedStr = str.split('').reverse().join('');
console.log(reversedStr); // Output: "olleh"
Q4: How do you check if a string contains a substring in JavaScript?
Answer: Use the includes()
method or indexOf()
.
let str = "Hello, world!";
console.log(str.includes("world")); // Output: true
console.log(str.indexOf("world") !== -1); // Output: true
Q5: How can you convert a string to uppercase and lowercase in JavaScript?
Answer: Use the toUpperCase()
and toLowerCase()
methods.
let str = "Hello";
console.log(str.toUpperCase()); // Output: "HELLO"
console.log(str.toLowerCase()); // Output: "hello"
Q6: How would you replace all occurrences of a substring in a string?
Answer: Use the replaceAll()
method (ES2021), or with a regular expression and the replace()
method.
let str = "foo foo bar";
console.log(str.replaceAll("foo", "baz")); // Output: "baz baz bar"
// Before ES2021, with regex:
console.log(str.replace(/foo/g, "baz")); // Output: "baz baz bar"
Q7: How do you extract a portion of a string without modifying the original string?
Answer: You can use slice()
, substring()
, or substr()
to extract a portion without changing the original string.
let str = "foo foo bar";
console.log(str.replaceAll("foo", "baz")); // Output: "baz baz bar"
// Before ES2021, with regex:
console.log(str.replace(/foo/g, "baz")); // Output: "baz baz bar"
Q8: What is template literal in JavaScript and how do you use it?
Answer: Template literals are a new way to create strings in ES6 using backticks (`
). They support multi-line strings and variable interpolation.
Q9: What is template literal in JavaScript and how do you use it?
Answer:
In JavaScript, there are two ways to create strings: string literals and string objects.
A string literal is a simple and most common way to create a string using single quotes (‘ ‘), double quotes (” “), or backticks (` `).
A string object is created using the new String() constructor, which wraps a primitive string into an object.
typeof "Hello"; // "string" (literal)
typeof new String("Hello"); // "object"
Q10: How can you split a string into an array in JavaScript?
Answer: Use the split()
method, specifying the delimiter.
let str = "apple, banana, cherry";
let arr = str.split(", ");
console.log(arr); // Output: ["apple", "banana", "cherry"]
Q11: What are escape sequences in JavaScript strings?
Answer: Escape sequences allow you to insert special characters like \n
for new lines, \t
for tabs, etc.
let str = "Line1\nLine2";
console.log(str);
// Output:
// Line1
// Line2
Q11: What are escape sequences in JavaScript strings?
Answer: Escape sequences allow you to insert special characters like \n
for new lines, \t
for tabs, etc.
let str = "Line1\nLine2";
console.log(str);
// Output:
// Line1
// Line2
DSA-Based Interview Questions on Strings:
Q1: How would you check if two strings are anagrams?
Answer:
Two strings are anagrams if they contain the same characters with the same frequency. One way to do this is by sorting both strings and comparing them.
function areAnagrams(str1, str2) {
if (str1.length !== str2.length) return false;
return str1.split('').sort().join('') === str2.split('').sort().join('');
}
console.log(areAnagrams("listen", "silent")); // Output: true
console.log(areAnagrams("hello", "world")); // Output: false
Q2: How do you check if a string is a palindrome?
Answer:
A string is a palindrome if it reads the same backward and forward. You can reverse the string and check if it’s equal to the original string.
function isPalindrome(str) {
let reversedStr = str.split('').reverse().join('');
return str === reversedStr;
}
console.log(isPalindrome("madam")); // Output: true
console.log(isPalindrome("hello")); // Output: false
Q3: Find the first non-repeating character in a string.
Answer:
A string is a palindrome if it reads the same backward and forward. You can reverse the string and check if it’s equal to the original string.
function firstNonRepeatingChar(str) {
let charCount = {};
// Count the frequency of each character
for (let char of str) {
charCount[char] = (charCount[char] || 0) + 1;
}
// Find the first character with a count of 1
for (let char of str) {
if (charCount[char] === 1) return char;
}
return null; // If no unique character is found
}
console.log(firstNonRepeatingChar("swiss")); // Output: "w"
console.log(firstNonRepeatingChar("aabbxxyyzz")); // Output: null
Q4: How would you check if a string contains all unique characters?
Answer:
You can use a set to track the characters and check for duplicates.
function hasUniqueCharacters(str) {
let charSet = new Set();
for (let char of str) {
if (charSet.has(char)) return false;
charSet.add(char);
}
return true;
}
console.log(hasUniqueCharacters("abcdef")); // Output: true
console.log(hasUniqueCharacters("hello")); // Output: false
Q5: How do you remove duplicate characters from a string?
Answer:
You can use a set to store unique characters and then join them back into a string.
function removeDuplicates(str) {
let uniqueChars = new Set(str);
return [...uniqueChars].join('');
}
console.log(removeDuplicates("aabbcc")); // Output: "abc"
console.log(removeDuplicates("hello")); // Output: "helo"
Q6: How would you count and return the frequency of each character in a string?
Answer:
You can use a hash map (or object) to store the frequency of each character.
function characterFrequency(str) {
let frequency = {};
for (let char of str) {
frequency[char] = (frequency[char] || 0) + 1;
}
return frequency;
}
console.log(characterFrequency("hello"));
// Output: { h: 1, e: 1, l: 2, o: 1 }
Conclusion
In today’s fast-paced tech environment, preparing for JavaScript interviews is critical, especially when it comes to string manipulation and data structure and algorithm (DSA) challenges. By mastering key string-related concepts like reversing strings, checking palindromes, anagrams, and more complex algorithms like the longest common prefix, you’ll strengthen your problem-solving skills and boost your confidence during coding interviews.