Skip to curriculum
Jump to the editor

2.6. Count the characters between the first and last "X"

Easy
Topics

This question is in

2. Strings and text
5–15 min

Text often carries a value between two markers: a code between # signs, a quote between quotation marks, a field between pipes in a log line. Measuring the part between the first and the last marker is the first step of pulling it out, and it is a good test of the details: what if the marker appears once, appears in the middle, is several characters long, or the text holds emoji?

Write countBetween(text, marker) in count-between.js.

Signature

JAVASCRIPT
function countBetween(text, marker = "X") // a number of characters
  • text: the string to search.
  • marker: the text that marks both edges. "X" when it is left out.

Requirements

  1. Returns how many characters lie between the end of the first occurrence of marker and the start of its last occurrence: countBetween("abXcdeXf") is 3.
  2. Returns 0 when the marker occurs once or not at all, and when the two occurrences are next to each other.
  3. Every character between counts: spaces, punctuation, and markers in the middle ("XaXbX" gives 3).
  4. The search is case-sensitive: "x" is not "X".
  5. Characters are counted as code points: an emoji counts once.
  6. Any marker works, and it is plain text: "." matches only a dot.
  7. A marker of several characters is skipped whole: the count starts after the first occurrence ends. When the last occurrence starts before the first one ends (they overlap) or right where it ends, the result is 0.
  8. An empty marker throws a RangeError.
  9. A text of 200,000 characters is handled quickly.

Examples

JAVASCRIPT
countBetween("abXcdeXf");          // 3: "cde"
countBetween("XaXbX");             // 3: "aXb"
countBetween("abXcd");             // 0: only one X
countBetween("XπŸ˜€πŸ˜€X");            // 2
JAVASCRIPT
countBetween("a|bc|d", "|");       // 2
countBetween("<>a<>b<>", "<>");    // 4: "a<>b"
countBetween("XXX", "XX");         // 0: the two occurrences overlap
countBetween("abc", "");           // throws RangeError

Environment

  • Plain JavaScript in a browser page; the tests call the global countBetween from count-between.js.
  • text and marker are always strings.
  • Any built-in may be used.

Hints

  1. Is there a search method that starts from the end of the string?
  2. "XπŸ˜€X".lastIndexOf("X") - "XπŸ˜€X".indexOf("X") is 3. Why, and what would you count instead?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…