Code Snippets
/

String Tricks: Anagrams, Vowels, Masking, Extension Check, Find Duplicates, Extract Numbers

String Tricks: Anagrams, Vowels, Masking, Extension Check, Find Duplicates, Extract Numbers

A grab-bag of small string utilities pulled from a much larger pool: inspecting strings (anagram check, find duplicate characters, distinguish literal from object), counting and scanning (vowels via regex, extract numbers, extension check), transforming (mask the middle, generate alphabet ranges), and order-aware tricks (remove adjacent duplicates, reverse only words longer than n). Each is short on its own; together they cover most of the string work that shows up in real code.

JavaScript
Medium
4 snippets
strings
string-manipulation
regex
loops

906 views

16

// Case-insensitive anagram check: same characters, same counts.
const isAnagram = (a, b) => {
    const norm = (s) => s.toLowerCase().split('').sort().join('');
    return norm(a) === norm(b);
};

console.log(isAnagram('Listen', 'silent'));           // true
console.log(isAnagram('hello', 'world'));             // false
console.log(isAnagram('a gentleman', 'elegant man')); // false (whitespace counts)

// Find duplicate characters in a string with their counts.
const findDuplicateChars = (s) => {
    const counts = new Map();
    for (const ch of s) counts.set(ch, (counts.get(ch) ?? 0) + 1);
    const out = {};
    for (const [ch, n] of counts) if (n > 1) out[ch] = n;
    return out;
};

console.log(findDuplicateChars('programming'));
// { r: 2, g: 2, m: 2 }

// Distinguish a string from a String object (the boxed wrapper).
const isStringPrimitive = (x) => typeof x === 'string';
const isStringValue = (x) => typeof x === 'string' || x instanceof String;

console.log(isStringPrimitive('hi'));             // true
console.log(isStringPrimitive(new String('hi'))); // false (it is an object)
console.log(isStringValue(new String('hi')));     // true

The anagram check normalizes both strings (lowercase, sort characters, rejoin) and compares the results; whitespace counts as a character so 'a gentleman' is NOT an anagram of 'elegant man' until you strip spaces explicitly. The duplicate-character finder uses a Map to count occurrences in one pass and returns just the keys with counts above 1. The literal-vs-object distinction is rare but real: new String('hi') is a boxed object that survives typeof as 'object', so legacy code that uses new String needs the dual check (typeof === 'string' OR instanceof String). In modern code, never use new String; just use string literals.