JavaScript String Programming Interview Questions
String manipulation is a common topic in JavaScript interviews. Strings are fundamental in programming, and mastering their manipulation is crucial for solving various problems. This article compiles 20+ JavaScript string programming interview questions with detailed explanations, code examples, and outputs to help you prepare effectively.
01. How to reverse a string in JavaScript?
Reversing a string is a classic interview question. You can split the string into an array, reverse the array, and join it back into a string.
// Code Example:
function reverseString(str) {
return str.split('').reverse().join('');
}
// Example Usage:
console.log(reverseString("hello")); // Output: "olleh"
02. How to check if a string is a palindrome?
A palindrome reads the same backward as forward. Compare the original string with its reversed version.
// Code Example:
function isPalindrome(str) {
const reversed = str.split('').reverse().join('');
return str === reversed;
}
// Example Usage:
console.log(isPalindrome("madam")); // Output: true
console.log(isPalindrome("hello")); // Output: false
03. How to count the occurrences of a character in a string?
Use a loop or the split()
method to count occurrences.
// Code Example:
function countCharacter(str, char) {
return str.split(char).length - 1;
}
// Example Usage:
console.log(countCharacter("banana", "a")); // Output: 3
04. How to remove duplicate characters from a string?
Use a Set
to ensure each character is unique.
// Code Example:
function removeDuplicates(str) {
return [...new Set(str)].join('');
}
// Example Usage:
console.log(removeDuplicates("programming")); // Output: "progamin"
05. How to find the first non-repeating character in a string?
Use a frequency map to track occurrences.
// Code Example:
function firstNonRepeatingChar(str) {
const charCount = {};
for (let char of str) {
charCount[char] = (charCount[char] || 0) + 1;
}
for (let char of str) {
if (charCount[char] === 1) return char;
}
return null;
}
// Example Usage:
console.log(firstNonRepeatingChar("swiss")); // Output: "w"
06. How to capitalize the first letter of each word in a string?
Split the string by spaces, capitalize each word, and join it back.
// Code Example:
function capitalizeWords(str) {
return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
}
// Example Usage:
console.log(capitalizeWords("hello world")); // Output: "Hello World"
07. How to find all substrings of a string?
Use nested loops to extract all substrings.
// Code Example:
function getAllSubstrings(str) {
const substrings = [];
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j <= str.length; j++) {
substrings.push(str.slice(i, j));
}
}
return substrings;
}
// Example Usage:
console.log(getAllSubstrings("abc")); // Output: ["a", "ab", "abc", "b", "bc", "c"]
08. How to check if a string contains only digits?
Use a regular expression to validate.
// Code Example:
function isNumeric(str) {
return /^\d+$/.test(str);
}
// Example Usage:
console.log(isNumeric("12345")); // Output: true
console.log(isNumeric("123a")); // Output: false
09. How to replace all occurrences of a substring?
Use the replaceAll()
or replace()
with a global flag.
// Code Example:
function replaceAllOccurrences(str, search, replacement) {
return str.replaceAll(search, replacement);
}
// Example Usage:
console.log(replaceAllOccurrences("banana", "a", "o")); // Output: "bonono"
10. How to split a string into chunks of a specific size?
Use a loop to extract chunks.
// Code Example:
function splitIntoChunks(str, size) {
const chunks = [];
for (let i = 0; i < str.length; i += size) {
chunks.push(str.slice(i, i + size));
}
return chunks;
}
// Example Usage:
console.log(splitIntoChunks("abcdefgh", 3)); // Output: ["abc", "def", "gh"]
11. How to count words in a string?
Split the string by spaces or other delimiters to count the words.
// Code Example:
function countWords(str) {
return str.trim().split(/\s+/).length;
}
// Example Usage:
console.log(countWords("Hello world! How are you?")); // Output: 5
12. How to extract numbers from a string?
Use a regular expression to match digits and extract them.
// Code Example:
function extractNumbers(str) {
return str.match(/\d+/g).map(Number);
}
// Example Usage:
console.log(extractNumbers("I have 2 apples and 3 bananas.")); // Output: [2, 3]
13. How to convert a string to title case?
Capitalize the first letter of each word in the string.
// Code Example:
function toTitleCase(str) {
return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(' ');
}
// Example Usage:
console.log(toTitleCase("hello world")); // Output: "Hello World"
14. How to find the longest word in a string?
Split the string by spaces and compare the lengths of the words.
// Code Example:
function findLongestWord(str) {
return str.split(' ').reduce((longest, currentWord) => currentWord.length > longest.length ? currentWord : longest, "");
}
// Example Usage:
console.log(findLongestWord("I am learning JavaScript programming.")); // Output: "JavaScript"
15. How to reverse words in a string?
Split the string by spaces, reverse the array, and join it back into a string.
// Code Example:
function reverseWords(str) {
return str.split(' ').reverse().join(' ');
}
// Example Usage:
console.log(reverseWords("Hello world")); // Output: "world Hello"
16. How to compare two strings ignoring case?
Convert both strings to lowercase (or uppercase) before comparison.
// Code Example:
function compareStringsIgnoreCase(str1, str2) {
return str1.toLowerCase() === str2.toLowerCase();
}
// Example Usage:
console.log(compareStringsIgnoreCase("hello", "Hello")); // Output: true
17. How to check if a string ends with a specific substring?
Use the endsWith()
method to verify.
// Code Example:
function endsWithSubstring(str, substring) {
return str.endsWith(substring);
}
// Example Usage:
console.log(endsWithSubstring("JavaScript is fun", "fun")); // Output: true
18. How to find the maximum occurring character in a string?
Use a frequency map to track occurrences and find the maximum.
// Code Example:
function maxOccurringChar(str) {
const charCount = {};
for (let char of str) {
charCount[char] = (charCount[char] || 0) + 1;
}
return Object.keys(charCount).reduce((maxChar, char) => charCount[char] > charCount[maxChar] ? char : maxChar);
}
// Example Usage:
console.log(maxOccurringChar("programming")); // Output: "g"
19. How to pad a string to a specific length?
Use the padStart()
or padEnd()
method for padding.
// Code Example:
function padString(str, length, padChar = ' ') {
return str.padStart(length, padChar);
}
// Example Usage:
console.log(padString("hello", 10, "*")); // Output: "*****hello"
20. How to trim spaces from both ends of a string?
Use the trim()
method to remove spaces from both ends.
// Code Example:
function trimSpaces(str) {
return str.trim();
}
// Example Usage:
console.log(trimSpaces(" Hello world! ")); // Output: "Hello world!"
Conclusion
Mastering string manipulation is vital for JavaScript programming and technical interviews. These questions and examples cover various use cases, ensuring you’re well-prepared for challenges related to string processing.
Comments
Post a Comment