JavaScript String Manipulation Challenges
Six small-but-tricky string problems: longest-word slicing, list extraction, manual reversal, palindrome checks, anagram detection, and capitalizing every word.
516 views
8
Implement generateString(str, n) that finds the first word longer than its predecessor and joins it with the next n consecutive words (no separator).
Examples
Example 1:
Input: generateString('Hello, my fullname is john doe.', 2)
Output: 'fullnameisjohn'
Explanation: 'fullname' is the first word longer than its predecessor; concat with the next 2 words ('is', 'john') without spaces.function generateString(str, n) {
// your code here
}Write extractItems(str) that pulls the comma-separated list between : and . and returns a trimmed array of items.
Examples
Example 1:
Input: extractItems('Here is a list of items: book, chair, desk, pen. Thanks!')
Output: ['book', 'chair', 'desk', 'pen']
Explanation: Use `indexOf` to locate the delimiters, `substring` to slice between them, split on commas, then trim.function extractItems(str) {
// your code here
}Implement reverseWords(str) that reverses the word order without using split or reverse. Walk the string from the end.
Examples
Example 1:
Input: reverseWords('coding. js love I')
Output: 'I love js coding.'
Explanation: Scan right to left, accumulate characters, and on each space (or at index 0) flush the current word to the output.function reverseWords(str) {
// your code here, without split() or reverse()
}Implement isPalindrome(s) that ignores case and non-alphanumerics. Two-pointer or string-normalize both acceptable.
Examples
Example 1:
Input: isPalindrome('A man, a plan, a canal: Panama')
Output: true
Explanation: After lowercasing and stripping non-alphanumerics, the string reads the same forward and backward.function isPalindrome(s) {
// your code here
}Implement isAnagram(a, b) that returns true if a and b use the same letters with the same multiplicity. Ignore case and whitespace.
Examples
Example 1:
Input: isAnagram('Listen', 'Silent'), isAnagram('rail safety', 'fairy tales')
Output: true, true
Explanation: Lowercase, strip whitespace, sort the letters, then string-compare; or count characters with a hash map.function isAnagram(a, b) {
// your code here
}Write titleCase(str) that uppercases the first letter of every whitespace-separated word and lowercases everything else.
Examples
Example 1:
Input: titleCase('I'M A little tea pot')
Output: "I'm A Little Tea Pot"
Explanation: Split on whitespace, capitalize the first character of each word, lowercase the tail, then rejoin.function titleCase(str) {
// your code here
}