JavaScript Coding Problems Answers


25 Essential JavaScript String Manipulation Problems
Published: March 2024
In this comprehensive guide, we'll explore 25 essential JavaScript string manipulation problems that every developer should know. These problems cover a wide range of string operations, from basic manipulations to complex algorithms.
Basic String Operations
1. Reverse a String
function reverseString(str) {
return str.split("").reverse().join("");
}
Explanation: This solution splits the string into an array of characters, reverses the array, and joins it back into a string.
2. Check if a String is a Palindrome
function isPalindrome(str) {
const reversed = str.split("").reverse().join("");
return str === reversed;
}
Explanation: A palindrome reads the same forwards and backwards. This solution compares the original string with its reversed version.
3. Remove Duplicates from a String
function removeDuplicates(str) {
return [...new Set(str)].join("");
}
Explanation: Using Set to remove duplicate characters while preserving the order of first occurrence.
4. Find the First Non-Repeating Character
function firstNonRepeatingChar(str) {
for (let char of str) {
if (str.indexOf(char) === str.lastIndexOf(char)) return char;
}
return null;
}
Explanation: This solution finds the first character that appears only once in the string.
String Analysis
5. Count Character Occurrences
function charCount(str) {
const count = {};
for (let char of str) {
count[char] = (count[char] || 0) + 1;
}
return count;
}
Explanation: Creates a frequency map of all characters in the string.
6. Reverse Words in a Sentence
function reverseWords(sentence) {
return sentence.split(" ").reverse().join(" ");
}
Explanation: Reverses the order of words while maintaining the characters within each word.
7. Check if Two Strings are Anagrams
function areAnagrams(str1, str2) {
return str1.split("").sort().join("") === str2.split("").sort().join("");
}
Explanation: Two strings are anagrams if they contain the same characters in different orders.
Advanced String Manipulations
8. Longest Substring Without Repeating Characters
function longestUniqueSubstring(str) {
let maxLen = 0,
start = 0,
map = {},
longest = "";
for (let i = 0; i < str.length; i++) {
if (map[str[i]] !== undefined && map[str[i]] >= start) {
start = map[str[i]] + 1;
}
map[str[i]] = i;
if (i - start + 1 > maxLen) {
maxLen = i - start + 1;
longest = str.substring(start, i + 1);
}
}
return longest;
}
Explanation: Uses the sliding window technique to find the longest substring with unique characters.
9. String to Integer (atoi)
function myAtoi(str) {
const num = parseInt(str.trim(), 10);
return isNaN(num) ? 0 : num;
}
Explanation: Converts a string to an integer, handling edge cases and invalid inputs.
10. Run-Length Encoding
function runLengthEncoding(str) {
let result = "",
count = 1;
for (let i = 1; i <= str.length; i++) {
if (str[i] === str[i - 1]) {
count++;
} else {
result += str[i - 1] + count;
count = 1;
}
}
return result;
}
Explanation: Compresses a string by counting consecutive characters.
String Pattern Matching
11. Most Frequent Character
function mostFrequentChar(str) {
const freq = {};
for (let char of str) freq[char] = (freq[char] || 0) + 1;
return Object.keys(freq).reduce((a, b) => (freq[a] > freq[b] ? a : b));
}
Explanation: Finds the character that appears most frequently in the string.
12. All Substrings
function allSubstrings(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;
}
Explanation: Generates all possible substrings of a given string.
13. Check if a String is a Rotation of Another String
function isRotation(s1, s2) {
return s1.length === s2.length && (s1 + s1).includes(s2);
}
Explanation: Checks if one string is a rotation of another by concatenating the first string with itself and checking if it contains the second string.
14. Remove All White Spaces
function removeWhitespaces(str) {
return str.replace(/\s+/g, "");
}
Explanation: Removes all whitespace characters from a string using regular expressions.
15. Check if a String is a Valid Shuffle
function isValidShuffle(str1, str2, result) {
if (str1.length + str2.length !== result.length) return false;
let i = 0, j = 0, k = 0;
while (k < result.length) {
if (i < str1.length && str1[i] === result[k]) i++;
else if (j < str2.length && str2[j] === result[k]) j++;
else return false;
k++;
}
return i === str1.length && j === str2.length;
}
Explanation: Checks if a string is a valid shuffle of two other strings, maintaining the relative order of characters.
String Formatting
16. Title Case Conversion
function toTitleCase(str) {
return str
.toLowerCase()
.split(" ")
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
.join(" ");
}
Explanation: Converts a string to title case, capitalizing the first letter of each word.
17. Find the Longest Common Prefix
function longestCommonPrefix(strs) {
if (!strs.length) return "";
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
while (!strs[i].startsWith(prefix)) {
prefix = prefix.slice(0, -1);
if (!prefix) return "";
}
}
return prefix;
}
Explanation: Finds the longest common prefix among an array of strings.
18. Convert String to Character Array
function stringToCharArray(str) {
return str.split("");
}
Explanation: Converts a string into an array of individual characters.
19. URL Encoding
function urlEncode(str) {
return str.trim().replace(/ /g, "%20");
}
Explanation: Replaces spaces with %20 for URL encoding.
20. Acronym Generation
function acronym(str) {
return str
.split(" ")
.map((word) => word[0].toUpperCase())
.join("");
}
Explanation: Creates an acronym from the first letters of each word.
String Validation
21. Check for Digits Only
function containsOnlyDigits(str) {
return /^\d+$/.test(str);
}
Explanation: Checks if a string contains only numeric digits using regular expressions.
22. Count Words in String
function wordCount(str) {
return str.trim().split(/\s+/).length;
}
Explanation: Counts the number of words in a string, handling multiple spaces correctly.
23. Remove Specific Character
function removeChar(str, charToRemove) {
return str.split(charToRemove).join("");
}
Explanation: Removes all occurrences of a specific character from a string.
24. Find Shortest Word
function shortestWord(str) {
return str
.trim()
.split(/\s+/)
.reduce((shortest, word) =>
word.length < shortest.length ? word : shortest
);
}
Explanation: Finds the shortest word in a string using reduce to compare word lengths.
25. Find Longest Palindromic Substring
function longestPalindrome(s) {
let start = 0, end = 0;
const expand = (l, r) => {
while (l >= 0 && r < s.length && s[l] === s[r]) {
l--;
r++;
}
return [l + 1, r - 1];
};
for (let i = 0; i < s.length; i++) {
let [l1, r1] = expand(i, i),
[l2, r2] = expand(i, i + 1);
if (r1 - l1 > end - start) [start, end] = [l1, r1];
if (r2 - l2 > end - start) [start, end] = [l2, r2];
}
return s.substring(start, end + 1);
}
Explanation: Finds the longest palindromic substring using the expand-around-center technique.
Conclusion
These 25 string manipulation problems cover a wide range of common scenarios in JavaScript development. Understanding and implementing these solutions will help you become more proficient in string handling and problem-solving.
Remember that while these solutions are efficient, there might be multiple ways to solve each problem. The key is to understand the underlying concepts and choose the most appropriate solution for your specific use case.
Additional Resources
Note: This blog post is part of a series on JavaScript programming challenges. Stay tuned for more content on arrays, objects, and other JavaScript concepts.
Subscribe to my newsletter
Read articles from Chris Tiquis directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
