π§ JavaScript String Methods Reference
Parent: Strings JS Index
Complete Methods Reference
| Method | Description | Example |
|---|---|---|
s.length | String length | "hi".length β 2 |
s[i] / s.charAt(i) | Get char at index | "hi"[0] β 'h' |
s.at(i) | Get char (negative ok) | "hi".at(-1) β 'i' |
s.charCodeAt(i) | UTF-16 code of char | 'A'.charCodeAt(0) β 65 |
String.fromCharCode(n) | Char from code | String.fromCharCode(65) β 'A' |
s.slice(s,e) | Substring (end exclusive) | "hello".slice(1,3) β "el" |
s.substring(s,e) | Substring (no negatives) | |
s.indexOf(t) | First position | "hello".indexOf("l") β 2 |
s.lastIndexOf(t) | Last position | "hello".lastIndexOf("l") β 3 |
s.includes(t) | Contains? | "hello".includes("ell") β true |
s.startsWith(t) | Starts with? | "hello".startsWith("he") β true |
s.endsWith(t) | Ends with? | "hello".endsWith("lo") β true |
s.search(r) | Regex search β index | "hello".search(/l+/) β 2 |
s.match(r) | Regex match | "hi2".match(/\d/) β ['2'] |
s.matchAll(r) | All regex matches | requires /g flag |
s.replace(t,r) | Replace first | "aab".replace("a","X") β "Xab" |
s.replaceAll(t,r) | Replace all | "aab".replaceAll("a","X") β "XXb" |
s.toUpperCase() | Uppercase | "hi".toUpperCase() β "HI" |
s.toLowerCase() | Lowercase | "HI".toLowerCase() β "hi" |
s.trim() | Remove whitespace | " hi ".trim() β "hi" |
s.trimStart() | Trim start | |
s.trimEnd() | Trim end | |
s.split(d) | Split by delimiter | "a,b".split(",") β ['a','b'] |
s.repeat(n) | Repeat | "ab".repeat(3) β "ababab" |
s.padStart(n,p) | Pad left | "5".padStart(3,"0") β "005" |
s.padEnd(n,p) | Pad right | "5".padEnd(3,"0") β "500" |
s.concat(t) | Concatenate | "a".concat("b") β "ab" |
s.localeCompare(t) | Sort-safe compare | "a".localeCompare("b") β -1 |
s.normalize() | Unicode normalization | |
s.codePointAt(i) | Unicode code point | Handles emojis correctly |
Q1. Check If All Unique Characters
π§ How to Approach This
Step 1: Use a Set. If char already in Set β duplicate.
function hasAllUnique(s) {
const seen = new Set();
for (const c of s) {
if (seen.has(c)) return false;
seen.add(c);
}
return true;
}
console.log(hasAllUnique("hello")); // false
console.log(hasAllUnique("world")); // true
Time: O(n) | Space: O(k) charset
Q2. Pangram Check
function checkIfPangram(s) {
const lower = s.toLowerCase();
for (let i = 0; i < 26; i++) {
if (!lower.includes(String.fromCharCode(97 + i))) return false;
}
return true;
}
// More elegant with Set
function checkIfPangramSet(s) {
const letters = new Set(s.toLowerCase().replace(/[^a-z]/g, ''));
return letters.size === 26;
}
console.log(checkIfPangram("The quick brown fox jumps over the lazy dog")); // true
Q3. Most Frequent Character
function mostFrequent(s) {
const freq = new Map();
for (const c of s) freq.set(c, (freq.get(c) || 0) + 1);
return [...freq.entries()].reduce((a, b) => b[1] > a[1] ? b : a)[0];
}
console.log(mostFrequent("aabbbcc")); // 'b'
Q4. Remove Duplicates (Preserve Order)
function removeDuplicates(s) {
return [...new Set(s)].join('');
}
console.log(removeDuplicates("programming")); // "progamin"
Q5. Caesar Cipher
function caesarCipher(s, shift) {
return s.split('').map(c => {
if (c >= 'a' && c <= 'z') {
return String.fromCharCode((c.charCodeAt(0) - 97 + shift) % 26 + 97);
} else if (c >= 'A' && c <= 'Z') {
return String.fromCharCode((c.charCodeAt(0) - 65 + shift) % 26 + 65);
}
return c;
}).join('');
}
console.log(caesarCipher("Hello", 3)); // "Khoor"
console.log(caesarCipher("Khoor", 23)); // "Hello"
Q6. Check Balanced Brackets
function isBalanced(s) {
const stack = [];
const map = {')':'(', ']':'[', '}':'{'};
for (const c of s) {
if ('([{'.includes(c)) { stack.push(c); }
else if (map[c]) {
if (!stack.length || stack.pop() !== map[c]) return false;
}
}
return stack.length === 0;
}
console.log(isBalanced("({[]})")); // true
console.log(isBalanced("([)]")); // false
Q7. First Non-Repeating Character
function firstUniqChar(s) {
const freq = new Map();
for (const c of s) freq.set(c, (freq.get(c) || 0) + 1);
for (let i = 0; i < s.length; i++) {
if (freq.get(s[i]) === 1) return i;
}
return -1;
}
console.log(firstUniqChar("leetcode")); // 0
console.log(firstUniqChar("aabb")); // -1
Q8. String Compression
function compressString(s) {
if (!s) return s;
let result = '', count = 1;
for (let i = 1; i <= s.length; i++) {
if (i < s.length && s[i] === s[i-1]) { count++; continue; }
result += s[i-1] + count;
count = 1;
}
return result.length < s.length ? result : s;
}
console.log(compressString("aabcccccaaa")); // "a2b1c5a3"
console.log(compressString("abc")); // "abc"
Q9. Count Vowels and Consonants
function countVowCon(s) {
let vowels = 0, consonants = 0;
for (const c of s.toLowerCase()) {
if ('aeiou'.includes(c)) vowels++;
else if (c >= 'a' && c <= 'z') consonants++;
}
return { vowels, consonants };
}
console.log(countVowCon("Hello World")); // {vowels:3, consonants:7}
Q10. String Template Formatting
// Zero-pad number
const pad = (n, len) => String(n).padStart(len, '0');
console.log(pad(42, 5)); // "00042"
// Format money
const money = (n) => `$${n.toFixed(2)}`;
console.log(money(1234.5)); // "$1234.50"
// URL slug
const slug = (s) => s.toLowerCase().trim().replace(/\s+/g, '-').replace(/[^\w-]/g, '');
console.log(slug("Hello World!")); // "hello-world"
ES6+ String Features
// Optional chaining with strings
const obj = { name: "Alice" };
obj?.name?.toUpperCase(); // "ALICE"
obj?.missing?.toUpperCase(); // undefined (no error)
// String coercion
String(42); // "42"
String(null); // "null"
String(undefined); // "undefined"
(42).toString(); // "42"
(255).toString(16); // "ff" (hex)
(8).toString(2); // "1000" (binary)
// Number from string
parseInt("42"); // 42
parseInt("0xff", 16); // 255
parseFloat("3.14"); // 3.14
Number("42"); // 42
+"42"; // 42 (unary +)
// Nullish coalescing with string
const s = "" ?? "default"; // "" (empty string is NOT nullish)
const s2 = null ?? "default"; // "default"
const s3 = "" || "default"; // "default" (empty string IS falsy)