Solve JavaScript string programs: palindrome, anagram, reverse, capitalize, count vowels, remove duplicates, and common coding interview string problems with complete solutions.
How to Use This Guide
For each program:
- Understand the problem clearly
- Think of the approach before looking at the code
- Read the solution with comments
- Verify with the output
- Try the challenge variation yourself
Program 2 — Check Palindrome
A palindrome reads the same forwards and backwards.
function isPalindrome(str) {
// Normalize: lowercase + remove non-alphanumeric
const clean = str.toLowerCase().replace(/[^a-z0-9]/g, "");
const reversed = clean.split("").reverse().join("");
return clean === reversed;
}
console.log(isPalindrome("racecar")); // true
console.log(isPalindrome("hello")); // false
console.log(isPalindrome("A man a plan a canal Panama")); // true
console.log(isPalindrome("Never odd or even")); // true
Program 3 — Count Vowels and Consonants
function countVowelsConsonants(str) {
const letters = str.toLowerCase().replace(/[^a-z]/g, "");
const vowels = letters.match(/[aeiou]/g) || [];
const consonants = letters.match(/[^aeiou]/g) || [];
return {
vowels: vowels.length,
consonants: consonants.length,
vowelChars: vowels.join(""),
consonantChars: consonants.join("")
};
}
const result = countVowelsConsonants("JavaScript Master");
console.log(result);
{
vowels: 5,
consonants: 9,
vowelChars: 'aaae',
consonantChars: 'vScrptMstr'
}
Program 4 — Check Anagram
Two words are anagrams if they contain the same characters in any order.
function isAnagram(str1, str2) {
const normalize = s => s.toLowerCase().replace(/\s/g, "").split("").sort().join("");
return normalize(str1) === normalize(str2);
}
console.log(isAnagram("listen", "silent")); // true
console.log(isAnagram("hello", "world")); // false
console.log(isAnagram("Astronomer", "Moon starer")); // true
console.log(isAnagram("Dormitory", "Dirty room")); // true
Program 5 — Capitalize First Letter of Each Word (Title Case)
function titleCase(str) {
return str
.toLowerCase()
.split(" ")
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ");
}
// Using regex
function titleCaseRegex(str) {
return str.toLowerCase().replace(/\b\w/g, c => c.toUpperCase());
}
console.log(titleCase("the javascript master course"));
console.log(titleCaseRegex("hello world from wohotech"));
The Javascript Master Course
Hello World From Wohotech
Program 6 — Convert to camelCase
function toCamelCase(str) {
return str
.toLowerCase()
.replace(/[_\-\s]+(\w)/g, (_, char) => char.toUpperCase());
}
console.log(toCamelCase("hello world"));
console.log(toCamelCase("get_user_by_id"));
console.log(toCamelCase("background-color"));
console.log(toCamelCase("first name last name"));
helloWorld
getUserById
backgroundColor
firstNameLastName
Program 7 — Count Word Frequency
function wordFrequency(str) {
return str
.toLowerCase()
.replace(/[^a-z\s]/g, "") // remove punctuation
.split(/\s+/) // split by whitespace
.filter(Boolean) // remove empty strings
.reduce((freq, word) => {
freq[word] = (freq[word] || 0) + 1;
return freq;
}, {});
}
const text = "the quick brown fox jumps over the lazy dog the fox";
const freq = wordFrequency(text);
console.log(freq);
// Sort by frequency
const sorted = Object.entries(freq).sort(([, a], [, b]) => b - a);
console.log("Most common:", sorted.slice(0, 3));
{
the: 3,
quick: 1,
brown: 1,
fox: 2,
jumps: 1,
over: 1,
lazy: 1,
dog: 1
}
Most common: [ [ 'the', 3 ], [ 'fox', 2 ], [ 'quick', 1 ] ]
Program 8 — Remove Duplicate Characters
function removeDuplicates(str) {
return [...new Set(str)].join("");
}
// Preserve order explicitly
function removeDuplicatesPreserve(str) {
return str.split("").filter((char, idx, arr) => arr.indexOf(char) === idx).join("");
}
console.log(removeDuplicates("programming"));
console.log(removeDuplicates("aabbccdd"));
console.log(removeDuplicatesPreserve("javascript"));
Program 9 — Truncate String with Ellipsis
function truncate(str, maxLength, suffix = "...") {
if (str.length <= maxLength) return str;
return str.slice(0, maxLength - suffix.length) + suffix;
}
// Word-aware truncation (don't cut mid-word)
function truncateWords(str, maxLength) {
if (str.length <= maxLength) return str;
return str.slice(0, str.lastIndexOf(" ", maxLength)) + "...";
}
const long = "JavaScript is a versatile programming language used everywhere";
console.log(truncate(long, 30));
console.log(truncateWords(long, 30));
JavaScript is a versatile pro...
JavaScript is a versatile...
Program 10 — Find the Longest Word
function longestWord(sentence) {
const words = sentence.split(/\s+/);
return words.reduce((longest, word) =>
word.length > longest.length ? word : longest
, "");
}
// Return all words tied for longest
function allLongestWords(sentence) {
const words = sentence.split(/\s+/);
const maxLen = Math.max(...words.map(w => w.length));
return words.filter(w => w.length === maxLen);
}
console.log(longestWord("The quick brown fox jumps over"));
console.log(allLongestWords("I love cool code"));
jumps
[ 'love', 'cool', 'code' ]
Program 11 — Compress / Run-Length Encode a String
function compressString(str) {
let result = "";
let count = 1;
for (let i = 0; i < str.length; i++) {
if (str[i] === str[i + 1]) {
count++;
} else {
result += count > 1 ? str[i] + count : str[i];
count = 1;
}
}
// Return compressed only if shorter
return result.length < str.length ? result : str;
}
console.log(compressString("aaabbbccdd"));
console.log(compressString("aabbcc"));
console.log(compressString("abcd")); // no compression benefit
function extractNumbers(str) {
const matches = str.match(/\d+\.?\d*/g) || [];
return matches.map(Number);
}
const receipt = "Item 1: ₹150, Item 2: ₹299.50, Tax: ₹44.95";
const numbers = extractNumbers(receipt);
console.log(numbers);
console.log("Total:", numbers.reduce((s, n) => s + n, 0).toFixed(2));
[ 1, 150, 2, 299.5, 44.95 ]
Total: 497.45
Program 13 — Generate URL Slug
function generateSlug(title) {
return title
.toLowerCase()
.trim()
.replace(/[^a-z0-9\s-]/g, "") // remove special chars
.replace(/\s+/g, "-") // spaces to hyphens
.replace(/-{2,}/g, "-"); // multiple hyphens to one
}
console.log(generateSlug("JavaScript Master Course 2026!"));
console.log(generateSlug(" How to use React & Node.js? "));
console.log(generateSlug("Top 10 ES6 Features: What You Need"));
javascript-master-course-2026
how-to-use-react-nodejs
top-10-es6-features-what-you-need
Program 14 — Caesar Cipher (Encrypt/Decrypt)
function caesarCipher(str, shift) {
return str.replace(/[a-zA-Z]/g, char => {
const base = char >= "a" ? 97 : 65; // lowercase: 97, uppercase: 65
return String.fromCharCode(((char.charCodeAt(0) - base + shift) % 26) + base);
});
}
const message = "Hello JavaScript";
const encrypted = caesarCipher(message, 3);
const decrypted = caesarCipher(encrypted, -3);
console.log("Original:", message);
console.log("Encrypted:", encrypted);
console.log("Decrypted:", decrypted);
Original: Hello JavaScript
Encrypted: Khoor MdydVfulsw
Decrypted: Hello JavaScript
Program 15 — Validate Email (Basic)
function isValidEmail(email) {
const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return pattern.test(email);
}
const emails = [
"user@example.com",
"invalid-email",
"user@.com",
"user@domain.co.in",
"@nodomain.com",
"user@domain"
];
emails.forEach(e => console.log(`${e}: ${isValidEmail(e)}`));
user@example.com: true
invalid-email: false
user@.com: false
user@domain.co.in: true
@nodomain.com: false
user@domain: false
Common Patterns Summary
| Problem | Core Technique |
|---|
| Reverse string | split("").reverse().join("") |
| Palindrome check | Reverse and compare |
| Anagram check | Sort characters and compare |
| Capitalize words | split(" ").map(w => w[0].toUpperCase() + w.slice(1)).join(" ") |
| camelCase | replace(/[_\-\s]+(\w)/g, (_, c) => c.toUpperCase()) |
| Word frequency | reduce into object |
| Remove duplicates | [...new Set(str)].join("") |
| Find pattern | match(/regex/g) |
| Replace pattern | replace(/regex/g, replacement) |
| Slug generation | .toLowerCase().replace(/\s+/g, "-") |
Interview Questions 🎯
Q1. Write a function to check if a string is a palindrome. > Reverse the string and compare: str === str.split("").reverse().join(""). For real-world use, normalize case and remove non-alphanumeric characters first.
Q2. How do you check if two strings are anagrams? > Sort both strings' characters and compare: str1.split("").sort().join("") === str2.split("").sort().join("").
Q3. How do you count the occurrences of a character in a string? > str.split(char).length - 1 or (str.match(new RegExp(char, "g")) || []).length.
Q4. How do you reverse words in a sentence (not characters)? > sentence.split(" ").reverse().join(" ").
Q5. How do you find the most frequently occurring character? > Build a frequency object with reduce, then find the key with the highest value using Object.entries() and sort or reduce.
Q6. What is run-length encoding? > Compressing repeated characters: "aaabbb" → "a3b3". Count consecutive identical characters and store count + character.
Q7. How do you convert a string to title case? > .split(" ").map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(" ").
Key Takeaways 🏁
split("").reverse().join("") is the classic reverse string idiom- Sorting characters is the cleanest way to check anagrams
reduce into an object is the pattern for word/character frequencynew Set() gives you unique characters efficiently for deduplicationmatch(/regex/g) returns an array of all matches — powerful for extraction- String problems in interviews usually combine split, map, filter, reduce, and join
- Practice these 15 programs and you'll be ready for most string-based coding questions