Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT
2.6. Count the characters between the first and last "X"
Easy
Topics
This question is in
2. Strings and textText 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
function countBetween(text, marker = "X") // a number of characterstext: the string to search.marker: the text that marks both edges."X"when it is left out.
Requirements
- Returns how many characters lie between the end of the first occurrence of
markerand the start of its last occurrence:countBetween("abXcdeXf")is 3. - Returns 0 when the marker occurs once or not at all, and when the two occurrences are next to each other.
- Every character between counts: spaces, punctuation, and markers in the middle (
"XaXbX"gives 3). - The search is case-sensitive:
"x"is not"X". - Characters are counted as code points: an emoji counts once.
- Any marker works, and it is plain text:
"."matches only a dot. - 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.
- An empty marker throws a
RangeError. - A text of 200,000 characters is handled quickly.
Examples
countBetween("abXcdeXf"); // 3: "cde"
countBetween("XaXbX"); // 3: "aXb"
countBetween("abXcd"); // 0: only one X
countBetween("XππX"); // 2countBetween("a|bc|d", "|"); // 2
countBetween("<>a<>b<>", "<>"); // 4: "a<>b"
countBetween("XXX", "XX"); // 0: the two occurrences overlap
countBetween("abc", ""); // throws RangeErrorEnvironment
- Plain JavaScript in a browser page; the tests call the global
countBetweenfromcount-between.js. textandmarkerare always strings.- Any built-in may be used.
Hints
- Is there a search method that starts from the end of the string?
"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β¦