String Manipulation
Concept
Because strings are immutable, manipulating them requires specialized techniques.
In technical interviews, you are frequently asked to reverse strings, split them into words, or remove specific characters.
The most robust, universal pattern for complex string manipulation in JavaScript/Python is:
- Explode the string into a mutable Array of characters.
- Manipulate the Array using Two Pointers, sorting, or filtering.
- Implode the Array back into a String.
Reversing a String
While s.split("").reverse().join("") is a one-liner in JS, interviewers will often ask you to write the actual algorithmic logic yourself to prove you understand Two Pointers.
function reverseString(s: string): string {
// 1. Explode to array (O(N) space)
const arr = s.split("");
// 2. Manipulate (Two Pointers)
let left = 0;
let right = arr.length - 1;
while (left < right) {
let temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
// 3. Implode
return arr.join("");
}
Reversing Words in a String
Problem: Given “the sky is blue”, return “blue is sky the”.
Approach 1: The Built-in Methods (O(N) Space)
function reverseWords(s: string): string {
// Split by spaces, filter out empty strings (handling multiple spaces), reverse, and join
return s.trim().split(/\s+/).reverse().join(" ");
}
Approach 2: The Two-Pass Reversal (The C++ Space way)
If you were in C++, you would do this without allocating extra arrays:
- Reverse the entire string: “eulb si yks eht”.
- Iterate through the string, and whenever you find a space, reverse the individual word sitting right before it: “blue is sky the”.
Removing Vowels
Problem: Remove all vowels from a string.
function removeVowels(s: string): string {
const vowels = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']);
const result: string[] = []; // Using an array as a builder
for (let char of s) {
if (!vowels.has(char)) {
result.push(char);
}
}
return result.join("");
}
Interview Questions
Q: A developer needs to check if a string contains only digits. They use parseInt(s) !== NaN. Is this a safe approach?
A: No. parseInt stops parsing the moment it hits a non-digit character. parseInt("123apples") will successfully return 123, masking the fact that the string contained invalid text.
The safest approach is using a Regular Expression: /^\d+$/.test(s). Alternatively, you can loop through the string and check if the ASCII code of every character falls strictly between 48 (0) and 57 (9).
Q: You need to replace all instances of “apple” with “orange” in a string. How do you do it in JavaScript?
A: In older JS environments, s.replace("apple", "orange") only replaced the very first occurrence. To replace all occurrences, you had to use a Regex with the global flag: s.replace(/apple/g, "orange"), or the split/join hack: s.split("apple").join("orange").
Modern JavaScript (ES2021) finally introduced s.replaceAll("apple", "orange"), which is now the preferred, safest standard.