These are the notes for JavaScript Coding Questions, episode 13, interview and placement practice for people who finished the SyntaxPilot JavaScript course. Three string questions that look easy and each hide a trap: capitalize every word, convert names between camelCase and snake_case, and count words when the text has extra spaces. Along the way we go properly into a tool episode 11 only touched: regular expressions (regex).
Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.
Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. Plain modern JavaScript, no packages.
Q1: Capitalize every word
Problem. Make the first letter of every word upper case and the rest lower case. Keep the spaces exactly as they are.
"rahul sharma" → "Rahul Sharma"
"hELLO wORLD" → "Hello World" (caps lock left on)
"chai and samosa" → "Chai And Samosa" (two spaces kept)
"" → ""
Real life: a print shop making wedding cards from a guest list typed in a hurry.
Think out loud
- Input: a string. Output: a new string (strings in JavaScript can't be changed in place).
- Edge cases: two spaces in a row, an empty string, letters after the first that are capitals, apostrophes (
don't,rahul's).
The obvious attempt: split(" ") and w[0]
function capitalize(s) {
return s.split(" ")
.map(w => w[0].toUpperCase() + w.slice(1))
.join(" ");
}
console.log(capitalize("rahul sharma"));
console.log(capitalize("hELLO wORLD"));
console.log(capitalize("chai and samosa"));
Rahul Sharma
HELLO WORLD
main.js:3
.map(w => w[0].toUpperCase() + w.slice(1))
^
TypeError: Cannot read properties of undefined (reading 'toUpperCase')
Two bugs:
- The rest of the word is never lower-cased, so
hELLObecomesHELLO. "chai and samosa".split(" ")is["chai", "", "and", "", "samosa"]: two spaces leave an empty string between them.""[0]isundefined, andundefined.toUpperCase()throws a TypeError.
Fix: charAt(0) and slice(1).toLowerCase()
charAt(0) returns "" (not undefined) for an empty string, and "".toUpperCase() is just "".
function capitalize(s) {
return s.split(" ")
.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
.join(" ");
}
console.log(capitalize("rahul sharma"));
console.log(capitalize("hELLO wORLD"));
console.log(JSON.stringify(capitalize("chai and samosa")));
console.log(JSON.stringify(capitalize("")));
Rahul Sharma
Hello World
"Chai And Samosa"
""
JSON.stringify adds quotes so you can see the spaces and the empty string.
Complexity: O(n) time, O(n) space (the array of words and the new string).
Regular expressions in two minutes
A regular expression (regex) is a pattern that describes text. You write it between slashes. str.replace(regex, replacement) changes every piece of str that matches (every piece only with the g flag).
| Piece | Matches | Example |
|---|---|---|
\s |
one whitespace character: space, tab \t, newline \n |
/\s/ |
\S |
one character that is not whitespace | /\S/ |
\w |
one word character: letter, digit or _ |
/\w/ |
\d |
one digit | /\d/ |
[A-Z], [a-z0-9] |
one character from the set (a character class) | /[A-Z]/ |
+ |
one or more of the thing before it | /\s+/ |
^ |
the start of the text | /^a/ |
a\|b |
a or b |
/(^\|\s)/ |
( ) |
a group: part of the match you can reuse | /(\w)(\d)/ |
\b |
a word boundary: the position between a \w and a non-\w character (not a character itself) |
/\b\w/ |
g flag |
global: every match, not only the first | /x/g |
The replacement can be a string ("$1_$2" reuses group 1 and group 2) or a callback function: it is called for every match with (match, group1, group2, ...) and returns the text to put in its place.
The popular one-liner, and the \b trap
const capitalize = s => s.toLowerCase().replace(/\b\w/g, c => c.toUpperCase());
console.log(capitalize("rahul sharma"));
console.log(capitalize("don't stop, it's rahul's chai"));
Rahul Sharma
Don'T Stop, It'S Rahul'S Chai
The apostrophe is not a word character, so there is a word boundary between ' and t, and t is treated as the start of a word.
Fix: say what you mean, "start or whitespace, then a non-space"
const capitalize = s => s.toLowerCase().replace(/(^|\s)\S/g, m => m.toUpperCase());
console.log(capitalize("rahul sharma"));
console.log(capitalize("don't stop, it's rahul's chai"));
console.log(JSON.stringify(capitalize(" chai and\tsamosa")));
console.log(JSON.stringify(capitalize("")));
Rahul Sharma
Don't Stop, It's Rahul's Chai
" Chai And\tSamosa"
""
The match is either one character (at the start) or a whitespace character plus the letter; upper-casing a space leaves it a space. Complexity: O(n) time, O(n) space.
Q2: camelCase ↔ snake_case
Problem. Convert names made of several words between the two common styles:
- camelCase: words joined, every word after the first starts with a capital (the "humps"). JavaScript variables use it:
totalAmountPaid. - snake_case: all small letters, words joined with
_. Python and most database columns use it:total_amount_paid.
toSnake("userName") → "user_name"
toSnake("totalAmountPaid") → "total_amount_paid"
toSnake("address2") → "address2"
toSnake("userID") → "user_id"
toSnake("parseXMLFile") → "parse_xml_file"
toCamel("total_amount_paid") → "totalAmountPaid"
Real life: a shop's app form sends totalAmountPaid, the database column is total_amount_paid; every request converts the names.
The obvious attempt: "is it a capital?"
function toSnake(s) {
let out = "";
for (const c of s) {
if (c === c.toUpperCase()) out += "_" + c.toLowerCase();
else out += c;
}
return out;
}
console.log(toSnake("userName"));
console.log(toSnake("totalAmountPaid"));
console.log(toSnake("address2"));
console.log(toSnake("userID"));
user_name
total_amount_paid
address_2
user_i_d
- A digit has no upper case:
"2".toUpperCase()is"2", so the test calls it a capital. - In
IDboth letters are capitals, so each gets its own underscore.
Fix: cut at the hump with capture groups
A hump is "a small letter or digit, then a capital": /([a-z0-9])([A-Z])/g. Put _ between the two groups.
const toSnake = s => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
console.log(toSnake("userName"));
console.log(toSnake("totalAmountPaid"));
console.log(toSnake("address2"));
console.log(toSnake("userID"));
console.log(toSnake("parseXMLFile"));
user_name
total_amount_paid
address2
user_id
parse_xmlfile
parseXMLFile breaks: inside XMLF there is no small letter before a capital. A second rule handles a run of capitals followed by a capitalized word: /([A-Z]+)([A-Z][a-z])/g cuts before the last capital.
const toSnake = s => s
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
.toLowerCase();
console.log(toSnake("userName"), toSnake("address2"));
console.log(toSnake("userID"), toSnake("parseXMLFile"));
console.log(toSnake("XMLHttpRequest"));
user_name address2
user_id parse_xml_file
xml_http_request
snake_case → camelCase, and the missing g
const toCamel = s => s.replace(/_([a-z])/, (m, c) => c.toUpperCase());
console.log(toCamel("user_name"));
console.log(toCamel("total_amount_paid"));
userName
totalAmount_paid
Without the g flag, replace stops after the first match. The callback receives the whole match m ("_a") and then group 1 c ("a").
const toCamel = s => s.toLowerCase().replace(/_([a-z0-9])/g, (m, c) => c.toUpperCase());
console.log(toCamel("user_name"));
console.log(toCamel("total_amount_paid"));
console.log(toCamel("USER_ID"), toCamel("address_2"));
const toSnake = s => s
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
.toLowerCase();
console.log(toCamel(toSnake("totalAmountPaid")));
userName
totalAmountPaid
userId address2
totalAmountPaid
Note the round trip is not always exact: userID → user_id → userId. Short forms in capitals lose their capitals, which is why many style guides write userId.
Complexity: each replace is one pass: O(n) time, O(n) space.
Q3: Count the words
Problem. Count the words in a text. A word is a run of characters that are not whitespace.
"chai is ready" → 3
" chai is ready " → 3
"chai\tis\nready" → 3
"" and " " → 0
Real life: a word limit on a form, or words per minute in a typing test.
The obvious attempt: split(" ").length
const countWords = s => s.split(" ").length;
console.log(countWords("chai is ready"));
console.log(countWords(" chai is ready "));
console.log(countWords(""));
3
9
1
" chai is ready ".split(" ") is ["", "", "chai", "", "", "is", "ready", "", ""]: every single space is a cut, so runs of spaces and spaces at the ends leave empty pieces. And "".split(" ") is [""], length 1.
The common fix that is still wrong: trim() + split(/\s+/)
const countWords = s => s.trim().split(/\s+/).length;
console.log(countWords("chai is ready"));
console.log(countWords(" chai is ready "));
console.log(countWords("chai\tis\nready"));
console.log(countWords(""));
console.log(countWords(" "));
3
3
3
1
1
split always returns at least one piece, so empty or blank text still counts as 1.
The idea underneath: count gap → word steps (coaches of a passing train)
You don't count the gaps between coaches; you add one when a new coach starts.
function countWords(s) {
let count = 0, inWord = false;
for (const c of s) {
const space = c === " " || c === "\t" || c === "\n";
if (!space && !inWord) count++;
inWord = !space;
}
return count;
}
console.log(countWords("chai is ready"));
console.log(countWords(" chai is ready "));
console.log(countWords("chai\tis\nready"));
console.log(countWords(""), countWords(" "));
3
3
3
0 0
O(n) time, O(1) extra space.
The built-in way: match(/\S+/g) with a fallback
const countWords = s => (s.match(/\S+/g) ?? []).length;
console.log(countWords("chai is ready"));
console.log(countWords(" chai is ready "));
console.log(countWords("chai\tis\nready"));
console.log(countWords(""), countWords(" "));
console.log("".match(/\S+/g));
3
3
3
0 0
null
match with a g regex returns an array of every match, or null when there is none (not []). Without ?? [], null.length would throw a TypeError. O(n) time, O(n) space (the array of words).
Complexity summary
| Question | Approach | Time | Extra space |
|---|---|---|---|
| Capitalize | split + w[0] |
O(n), crashes on "" |
O(n) |
| Capitalize | split + charAt(0) + toLowerCase |
O(n) | O(n) |
| Capitalize | replace(/(^\|\s)\S/g, ...) |
O(n) | O(n) |
| camel → snake | two replace calls with groups |
O(n) | O(n) |
| snake → camel | replace(/_([a-z0-9])/g, callback) |
O(n) | O(n) |
| Count words | gap → word loop | O(n) | O(1) |
| Count words | match(/\S+/g) ?? [] |
O(n) | O(n) |
Common mistakes (and the exact outputs)
| Mistake | Code | What you see | Why | Fix |
|---|---|---|---|---|
| Indexing an empty word | w[0].toUpperCase() after split(" ") |
TypeError: Cannot read properties of undefined (reading 'toUpperCase') |
two spaces leave "", and ""[0] is undefined |
w.charAt(0) |
| Not lower-casing the rest | w[0].toUpperCase() + w.slice(1) |
HELLO WORLD |
the rest is copied as typed | w.slice(1).toLowerCase() |
\b at apostrophes |
replace(/\b\w/g, ...) |
Don'T, Rahul'S |
' is not a word character |
/(^\|\s)\S/g |
| Digits as capitals | c === c.toUpperCase() |
address_2 |
digits equal their upper case | /([a-z0-9])([A-Z])/g |
| One underscore per capital | same loop | user_i_d |
every capital is treated as a hump | cut only after a small letter or digit |
| Capitals glued together | one hump rule | parse_xmlfile |
no small letter inside XMLF |
add /([A-Z]+)([A-Z][a-z])/g first |
No g flag |
replace(/_([a-z])/, ...) |
totalAmount_paid |
stops after the first match | add g |
| String pattern in replace | "a_b_c".replace("_", " ") |
a b_c |
a string pattern replaces only the first | replaceAll or /_/g |
| Splitting on one space | s.split(" ").length |
9 for " chai is ready " |
every space is a cut | count runs of non-space |
split on empty text |
s.trim().split(/\s+/).length |
1 for "" |
split returns at least [""] |
(s.match(/\S+/g) ?? []).length |
match without a fallback |
s.match(/\S+/g).length |
TypeError on "" |
match returns null |
?? [] |
Mini project: clean a form before saving it
A shop's sign-up form arrives in camelCase with messy text. Before saving it to the database: snake_case keys, a properly capitalized name with single spaces, and a word count for the bio with a limit of 10 words.
// Mini project: clean a form before saving it to the database
const toSnake = s => s
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
.toLowerCase();
const capitalize = s => (s.match(/\S+/g) ?? []).join(" ").toLowerCase().replace(/(^|\s)\S/g, m => m.toUpperCase());
const countWords = s => (s.match(/\S+/g) ?? []).length;
function toRow(form) {
const row = {};
for (const [key, value] of Object.entries(form)) row[toSnake(key)] = value;
row.full_name = capitalize(row.full_name);
row.bio_words = countWords(row.short_bio);
if (row.bio_words > 10) throw new Error("bio is too long: " + row.bio_words + " words");
return row;
}
console.log(toRow({ fullName: " priya RAO ", userID: 42, shortBio: " loves chai and code " }));
{
full_name: 'Priya Rao',
user_id: 42,
short_bio: ' loves chai and code ',
bio_words: 4
}
Joining the words with one space (match(/\S+/g).join(" ")) is also the standard way to collapse extra spaces.
Your turn: kebab-case → camelCase (solution)
CSS writes background-color; JavaScript's element.style wants backgroundColor.
Solution
The same as snake → camel, with - instead of _, and the g flag.
const toCamel = s => s.replace(/-([a-z0-9])/g, (m, c) => c.toUpperCase());
console.log(toCamel("background-color"));
console.log(toCamel("border-top-width"));
console.log(toCamel("color"), JSON.stringify(toCamel("")));
backgroundColor
borderTopWidth
color ""
O(n) time, O(n) space.
Practice questions (with solutions)
1. Title case that keeps small words small (except the first word).
Solution
const SMALL = new Set(["a", "an", "and", "of", "the", "in", "on", "to"]);
function titleCase(s) {
return s.toLowerCase().split(" ").map((w, i) =>
i > 0 && SMALL.has(w) ? w : w.charAt(0).toUpperCase() + w.slice(1)
).join(" ");
}
console.log(titleCase("the lord of the rings"));
console.log(titleCase("a tale OF two cities"));
The Lord of the Rings
A Tale of Two Cities
2. Count the sentences in a paragraph (a sentence ends with ., ! or ?; ... and ?! end only one sentence).
Solution
[^.!?]* is "any characters that are not an ending mark" (a ^ inside square brackets means not), and [.!?]+ is one or more ending marks.
const countSentences = s => (s.match(/[^.!?]*[.!?]+/g) ?? []).filter(x => x.trim() !== "").length;
console.log(countSentences("Chai is ready. Come fast! Are you coming?"));
console.log(countSentences("Wait... what?!"), countSentences(""));
3
2 0
3. Reverse the order of the words, ignoring extra spaces.
Solution
const reverseWords = s => (s.match(/\S+/g) ?? []).reverse().join(" ");
console.log(JSON.stringify(reverseWords(" chai is ready ")));
console.log(JSON.stringify(reverseWords("")));
"ready is chai"
""
4. Write countWords without a regex and without a flag variable.
Solution
A word starts at position i when s[i] is not whitespace and i is 0 or s[i - 1] is whitespace. Count those positions: the same gap → word idea, looking one character back instead of remembering a flag.
function countWords(s) {
const isSpace = c => c === " " || c === "\t" || c === "\n";
let count = 0;
for (let i = 0; i < s.length; i++) {
if (!isSpace(s[i]) && (i === 0 || isSpace(s[i - 1]))) count++;
}
return count;
}
console.log(countWords(" chai is ready "), countWords(""), countWords("one"));
3 0 1
O(n) time, O(1) space.
Quick quiz
1. (From the video.) What does this print?
console.log("chai_and_samosa".replace("_", " "));
(A) chai and samosa (B) chai and_samosa (C) chai_and samosa (D) chaiandsamosa
Answer
(B) chai and_samosa. With a string pattern, replace changes only the first match. "snake_case_here".replaceAll("_", " ") prints snake case here.
2. What does this print?
console.log("a b".split(" "));
console.log("".split(" ").length, "".split(/\s+/).length);
Answer
[ 'a', '', 'b' ]
1 1
3. What does this print?
console.log("x1y2".replace(/\d/g, d => d * 2));
Answer
x2y4
The callback runs once per digit; "1" * 2 is the number 2, which is turned back into text.
Interview questions
- Capitalize every word in a sentence.
split(" ")+charAt(0).toUpperCase()+slice(1).toLowerCase(), orreplace(/(^|\s)\S/g, m => m.toUpperCase()). - Why does
w[0].toUpperCase()crash? Double spaces produce empty strings, and""[0]isundefined. - What is
\b? A word boundary: a position between a word character and a non-word character, not a character. - Convert camelCase to snake_case.
/([a-z0-9])([A-Z])/g→"$1_$2", then lower case; add/([A-Z]+)([A-Z][a-z])/gfor short forms. - What does the
gflag do? Replace (or match) every occurrence, not only the first. - What does a
replacecallback receive? The whole match, then each group, then the position and the whole string. - Difference between
replaceandreplaceAllwith a string?replacechanges the first match,replaceAllevery match. - Count words with extra spaces.
(s.match(/\S+/g) ?? []).length, or count gap → word steps in O(1) space. - What does
matchreturn when nothing matches?null. \svs\Svs\w? Whitespace, not whitespace, word character (letter, digit, underscore).
Glossary
| Term | Meaning | Example |
|---|---|---|
| Capitalize | First letter upper case, the rest lower case | rahul → Rahul |
charAt(i) |
The character at i, or "" if there is none |
"".charAt(0) → "" |
str[i] |
The character at i, or undefined |
""[0] → undefined |
slice(1) |
Everything from index 1 to the end | "chai".slice(1) → "hai" |
toUpperCase / toLowerCase |
A new string in upper / lower case | "hI".toLowerCase() → "hi" |
split(sep) |
Cut a string into an array at every sep |
"a b".split(" ") → ["a", "b"] |
join(sep) |
Glue an array into a string | ["a", "b"].join("_") |
trim() |
Remove whitespace from both ends | " a ".trim() → "a" |
| Regular expression (regex) | A pattern that describes text | /\s+/ |
| Regex literal | A regex written between slashes | /[A-Z]/g |
| Whitespace | Space, tab \t, newline \n |
\s |
\s / \S |
One whitespace / non-whitespace character | /\S+/ |
\w / \d |
One word character / digit | /\w/ |
| Character class | A set of allowed characters in [ ] |
[a-z0-9] |
| Negated class | [^...]: any character not in the set |
[^.!?] |
Quantifier + |
One or more of the previous piece | \s+ |
Anchor ^ |
The start of the text | /^a/ |
Alternation \| |
Either side | (^\|\s) |
| Group / capture group | Part of a match in ( ) that can be reused |
([A-Z]) |
$1, $2 |
Group 1, group 2 in a replacement string | "$1_$2" |
Word boundary \b |
The position between \w and a non-\w |
/\b\w/ |
Flag g |
Global: every match | /_/g |
replace |
Replace the first match (every match with g) |
s.replace(/a/g, "b") |
replaceAll |
Replace every match of a string or g regex |
s.replaceAll("_", " ") |
| Replace callback | A function that returns the replacement for each match | (m, c) => c.toUpperCase() |
match |
Array of matches with g, or null |
"".match(/\S+/g) → null |
| camelCase | Words joined, later words capitalized | totalAmountPaid |
| snake_case | Small letters joined with _ |
total_amount_paid |
| kebab-case | Small letters joined with - (CSS) |
background-color |
| Hump | Where a small letter meets a capital | t\|A in totalAmount |
Nullish coalescing ?? |
Use the right side when the left is null/undefined |
null ?? [] → [] |
JSON.stringify |
Shows a string with quotes, so spaces are visible | '" a"' |
| TypeError | Using a value in a way its type doesn't allow | undefined.toUpperCase() |
| O(1) space | Extra memory that doesn't grow with the input | count, inWord |
Summary
- Capitalize:
w[0]isundefinedfor the empty words that double spaces create; usecharAt(0)and lower-case the rest. In a regex,\bbreaks at apostrophes;/(^|\s)\S/gsays exactly "the first character of each word". - Regex basics:
\s,\S,\w,[A-Z],+,^,|, groups( )reused as$1,$2or as callback arguments, and thegflag for every match. - camelCase ↔ snake_case: cut where a small letter or digit meets a capital (plus a rule for runs of capitals); back to camel with
/_([a-z0-9])/gand a callback. Forgettinggconverts only the first word. - Count words:
split(" ")andsplit(/\s+/)miscount extra spaces and empty text. Count gap → word steps (O(1) space) or use(s.match(/\S+/g) ?? []).length.
Next episode: String questions IV: the longest substring without repeating characters (sliding window), string compression (aabccc → a2b1c3), and valid parentheses with a stack.