JavaScript string exercises
JavaScript strings rarely throw errors. They just produce the wrong text: "5" + 1 is "51", replace() stops after one match, and ${name} in single quotes prints as-is. Each exercise here is a short function with one of those bugs.
Run the tests, read what came back, fix the line. Everything runs in a sandboxed worker in your browser.
The strings bugs you will meet
- replace() with a string pattern only replaces the first match; use replaceAll().
- ${} only works inside backticks.
- + with a string concatenates: "5" + 1 is "51".
- slice(0) returns the whole string, not everything after the first character.
- toFixed() returns a string, so adding to it concatenates.
The exercises
Easy
- Cart total shows "01020" instead of 30Type
- Capitalize turns "debug" into "Ddebug"Off-by-one
- Word counter shows NaNNull and undefined
- Correct PIN is rejectedType
- Digit sum gives "0123" instead of 6Type
- Palindrome check fails on capitalised wordsLogic
- Parsing string numbers with array map returns NaN and binaryType
- Removing dashes from phone number leaves trailing hyphensLogic
- Padding invoice number with padEnd appends trailing zeroesLogic
- Adding toFixed result to number performs string concatenationType
- Splitting empty string returns array with length oneLogic
- String substring with negative argument treats index as zeroLogic
- Sorting mixed case words orders capital letters before lowercaseLogic
- Query parameter false string converted to boolean evaluates to trueType
- Checking if order quantity is integer fails on string numbersType
- Empty string input coerced to zero by Number constructorType
- Parsing number with trailing letters produces partial integerType
- Malformed token string causes JSON parse to throw SyntaxErrorType
- Shout button doesn't shoutMutation and copying
- URL slug only replaces the first spaceLogic
Medium
- Vote total shows "034" instead of 7Type
- Word lengths come back as promises, not numbersAsync and race conditions
- Grouping words keeps only one per groupLogic
- Names list is full of promises, not textAsync and race conditions
- Counting matches always gives 0Scope and closure
- Counting capitals freezes on a lowercase letterInfinite loops
- 1.5 + 2.5 comes out as 3Type
- Joining words leaves a dash at the endOff-by-one
- Removing dashes removes only the first oneMutation and copying
- map(parseInt) turns "10" into NaN and 2Type
- Prices over 1,000 come out as 1Type
- AI Attempt: Character frequency counterNull and undefined
- AI Attempt: Title case crashes on a double spaceNull and undefined
Errors you might be searching for
More JavaScript practice by topic
Questions
Do I need Node.js?
No. Your code runs in a sandboxed Web Worker in the browser.
Which JavaScript version?
Plain modern JavaScript, with no frameworks. The same bugs turn up in React and Node code.