Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

extractAllBetween

Extracts all substrings found between two delimiters.

TypeScript
Copied!
1/**
2 * Extracts all substrings found between two delimiters.
3 *
4 * @param str - The input string.
5 * @param start - The starting delimiter.
6 * @param end - The ending delimiter.
7 * @returns An array of all substrings found between the delimiters.
8 *
9 * @example
10 * extractAllBetween('a [1] b [2]', '[', ']') => ['1', '2']
11 */
12export function extractAllBetween(
13  str: string,
14  start: string,
15  end: string
16): string[] {
17  const result: string[] = [];
18  let currentIndex = 0;
19
20  while (currentIndex < str.length) {
21    const startIdx = str.indexOf(start, currentIndex);
22    if (startIdx === -1) break;
23
24    const endIdx = str.indexOf(end, startIdx + start.length);
25    if (endIdx === -1) break;
26
27    result.push(str.slice(startIdx + start.length, endIdx));
28    currentIndex = endIdx + end.length;
29  }
30
31  return result;
32}
  • Multiple Matches Support

    Unlike a simple .match() or regex approach, this function extracts all non-overlapping substrings between given delimiters.

  • Custom Delimiters

    Works with any custom start and end markers, including multi-character delimiters.

  • Safe Iteration

    Manually iterates through the string with indexOf, avoiding pitfalls like infinite loops or overlapping captures.

  • No Regex Required

    Avoids complex regular expressions, making it easier to read, debug, and safer from injection issues.

  • Immutable Result

    Returns a clean, side-effect-free array that can be reused or transformed as needed.

Tests | Examples

TypeScript
Copied!
1test('extractAllBetween - multiple matches', () => {
2  expect(extractAllBetween('x[1]y[2]z[3]', '[', ']')).toEqual(['1', '2', '3']);
3});
4
5test('extractAllBetween - no matches', () => {
6  expect(extractAllBetween('abc', '[', ']')).toEqual([]);
7});
8
9test('extractAllBetween - partial match only', () => {
10  expect(extractAllBetween('a [1 b 2]', '[', ']')).toEqual([]);
11});
12
13test('extractAllBetween - same delimiters', () => {
14  expect(extractAllBetween('a|x|b|y|c', '|', '|')).toEqual(['x', 'y']);
15});
16
17test('extractAllBetween - nested brackets', () => {
18  expect(extractAllBetween('<<a><b>>', '<', '>')).toEqual(['<a', 'b']);
19});
20
21test('extractAllBetween - empty string', () => {
22  expect(extractAllBetween('', '[', ']')).toEqual([]);
23});

Common Use Cases

  • Parsing Custom Tags or Tokens

    Extract values from custom markup like [tag], {{variable}}, or <%= name %>.

  • Log File Analysis

    Extract fields enclosed in brackets, parentheses, or quotes from logs or structured text.

  • Template Processing

    Collect all variables inside delimiters for preprocessing or dynamic content replacement.

  • Data Extraction from Text

    Pull values between markers in semi-structured content (e.g. emails, user input, configuration files).

  • Input Sanitization or Isolation

    Identify and isolate specific content sections for validation or cleanup before further processing.

Codebase: Utilities -> Strings -> extractAllBetween | Yevhen Klymentiev