Basic · 12 of 12 · 14 min read
String and array handling
The string methods worth knowing by heart, how to cross between strings and arrays, and the small exercises interviewers use to test both.
- Strings
Strings are immutable primitives, so every string method returns a new string. The practical consequence is that string work is a pipeline: convert to an array, use the array methods, convert back.
Reading parts out
| Method | Returns | Negative indexes |
|---|---|---|
slice(start, end) |
a section | yes — counts from the end |
substring(start, end) |
a section | no — clamps to 0, then swaps the arguments |
at(i) |
one character | yes |
charAt(i) / [i] |
one character | no |
const s = 'JavaScript';
console.log(s.slice(0, 4)); // "Java"
console.log(s.slice(4)); // "Script"
console.log(s.slice(-6)); // "Script" — six from the end
console.log(s.slice(1, -1)); // "avaScrip"
console.log(s.substring(1, -1)); // "J" ← -1 clamped to 0, then swapped to (0, 1)
console.log(s.at(0), s.at(-1)); // "J" "t"
console.log(s[0], s.charAt(0)); // "J" "J"
console.log(s[99], s.at(99)); // undefined undefined
console.log(s.charAt(99)); // "" ← charAt differs here
slice is the one to default to: it handles negative indexes and behaves the same on arrays.
Searching
const s = 'JavaScript';
console.log(s.indexOf('Script')); // 4
console.log(s.indexOf('Python')); // -1 ← not undefined
console.log(s.lastIndexOf('a')); // 3
console.log(s.includes('Script')); // true — the clearer yes/no
console.log(s.startsWith('Java')); // true
console.log(s.endsWith('pt')); // true
console.log(s.search(/script/i)); // 4 — regex, returns an index
console.log(s.match(/a/g)); // ["a", "a"]
indexOf returning -1 is the trap, because -1 is truthy:
const s = 'hello';
if (s.indexOf('z')) console.log('this runs!'); // -1 is truthy — the bug
if (s.indexOf('z') !== -1) console.log('correct');
if (s.includes('z')) console.log('clearest'); // neither of these runs
Changing
Every one of these returns a new string.
const s = ' Hello World ';
console.log(s.trim()); // "Hello World"
console.log(s.trimStart().length); // 13
console.log(s.toUpperCase()); // " HELLO WORLD "
console.log('abc'.padStart(5, '0')); // "00abc"
console.log('ab'.repeat(3)); // "ababab"
console.log('a-b-c'.split('-')); // ["a", "b", "c"]
console.log(['a', 'b'].join('-')); // "a-b"
replace with a string pattern only changes the first match — the single most common string bug:
const s = 'a-b-c';
console.log(s.replace('-', '+')); // "a+b-c" ← first only
console.log(s.replaceAll('-', '+')); // "a+b+c"
console.log(s.replace(/-/g, '+')); // "a+b+c" — the pre-replaceAll way
console.log(s.split('-').join('+')); // "a+b+c" — also works
A replacement can be a function, which is how you transform each match:
console.log('a-b-c'.replace(/\w/g, (c) => c.toUpperCase())); // "A-B-C"
Crossing between strings and arrays
const s = 'hello world';
console.log(s.split(' ')); // ["hello", "world"] — on a separator
console.log(s.split('')); // ["h","e","l","l","o"," ","w","o","r","l","d"]
console.log([...s].length); // 11 — spread also splits into characters
console.log(Array.from(s).length); // 11
console.log(['hello', 'world'].join(' ')); // "hello world"
console.log(['a', 'b'].join('')); // "ab"
split('') and [...s] differ on characters outside the basic range — the spread respects code
points, split('') does not:
const emoji = 'a😀';
console.log(emoji.length); // 3 — the emoji is two code units
console.log(emoji.split('').length); // 3 ← splits the emoji in half
console.log([...emoji].length); // 2 ← correct
For anything user-facing, prefer the spread or Array.from.
The exercises
These are the ones that come up live. Each is split → transform → join.
Reverse a string
const reverse = (s) => [...s].reverse().join('');
console.log(reverse('hello')); // "olleh"
Reverse the letters of each word, keeping word order
const reverseEachWord = (sentence) =>
sentence
.split(' ')
.map((word) => [...word].reverse().join(''))
.join(' ');
console.log(reverseEachWord('hello world')); // "olleh dlrow"
Capitalise each word
const titleCase = (sentence) =>
sentence
.split(' ')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
console.log(titleCase('hELLO wORLD')); // "Hello World"
Count the characters
function countChars(s) {
return [...s].reduce((counts, char) => {
counts[char] = (counts[char] ?? 0) + 1;
return counts;
}, {});
}
console.log(countChars('hello')); // { h: 1, e: 1, l: 2, o: 1 }
Is it a palindrome?
const isPalindrome = (s) => {
const clean = s.toLowerCase().replace(/[^a-z0-9]/g, '');
return clean === [...clean].reverse().join('');
};
console.log(isPalindrome('A man, a plan, a canal: Panama')); // true
console.log(isPalindrome('hello')); // false
Longest word
const longest = (sentence) =>
sentence.split(' ').reduce((best, word) => (word.length > best.length ? word : best), '');
console.log(longest('the quick brown fox')); // "quick"
Truncate with an ellipsis
const truncate = (s, max) => (s.length <= max ? s : s.slice(0, max - 1) + '…');
console.log(truncate('hello world', 8)); // "hello w…"
console.log(truncate('short', 8)); // "short"
Template literals
Backticks interpolate and span lines, which is why they have replaced concatenation almost everywhere:
const name = 'Ana';
const items = ['a', 'b'];
console.log(`Hi ${name}, you have ${items.length} items`); // Hi Ana, you have 2 items
console.log(`2 + 2 = ${2 + 2}`); // 2 + 2 = 4 — any expression
const multi = `line one
line two`;
console.log(multi.split('\n').length); // 2 — real line breaks, no \n needed
They do not escape anything. Interpolating user input into HTML with a template literal is exactly how an XSS bug gets written.
Common mistakes
Expecting a string method to mutate
Mistake. name.trim(); on its own line, then using name.
Why it fails. Strings are immutable primitives; the method returned a new string that was
discarded.
What to do instead. Assign it: name = name.trim().
replace with a string pattern for every match
Mistake. path.replace('\\', '/') to normalise a Windows path.
Why it fails. Only the first separator changes.
What to do instead. replaceAll, or a global regex.
Treating indexOf’s result as a boolean
Mistake. if (s.indexOf(sub)).
Why it fails. -1 means “not found” and is truthy, while 0 means “found at the start” and is
falsy — so the check is wrong in both directions.
What to do instead. s.includes(sub).
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
Several string and array methods accept negative indexes, with a specific meaning.
What does this log?
console.log("hello".slice(-3));"hello".slice(1, -1) gives "ell". Why does "hello".substring(1, -1) give something else?
Passing a plain string as the pattern to replace does less than people expect.
What does this log?
console.log("a-b-c".replace("-", "+"));
console.log("a-b-c".replaceAll("-", "+"));Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.