Function within

  • within is a funny combinator. It finds zero or more instances of parser within the input. It always succeeds and returns an array of results, each one being a matched or unmatched string. You could think of "within" as a glorified search. For example, you can use it to look for quoted text or multiline comments within an input.

    Example:

      const multilineComments = seq(
    [str("/*"), manyWithJoin(noneOf(`*/`)), str("*/")],
    (results: string[]) => results.join("")
    );
    const parser = within(multilineComments);
    const input = `code before /* this is a comment */ code after /* another comment */ end`;

    const result = parser(input);
    console.log(JSON.stringify(result, null, 2));

    Result:

    {
    "success": true,
    "result": [
    {
    "type": "unmatched",
    "value": "code before "
    },
    {
    "type": "matched",
    "value": "/* this is a comment */"
    },
    {
    "type": "unmatched",
    "value": " code after "
    },
    {
    "type": "matched",
    "value": "/* another comment */"
    },
    {
    "type": "unmatched",
    "value": " end"
    }
    ],
    "rest": ""
    }

    This parser is somewhat expensive, as it will go down the input string one character at a time, applying the given parser each time.

    Type Parameters

    • T

    Parameters

    • parser: Parser<T>

      parser to find within the input

    Returns Parser<WithinResult<T>[]>

    • an array of matched and unmatched strings

Generated using TypeDoc