Nonchalant Programming Master

    find-matching-bracket
    TypeScript icon, indicating that this package has built-in type declarations

    1.0.3 • Public • Published

    find-matching-bracket

    Find matching bracket in Js/Ts/Cs code (including string Template literals interpolation)

    /**
     * if throwErrors is true, it throw (stop) with info.
     * else it return matching position,
     * or:
     * -2 if startPostion don't match start bracket
     * -3 if end bracket dont match start bracket
     * -1 if cursor comes to end of code without finding maching bracket
     *
     * @param code
     * @param startPosition position for staing bracket
     * @param throwErrors default false - if true: throw error with information
     * @returns
     */
    export default function matchBracket(code: string, startPosition: number, throwErrors = false): number;

    matchBracket example:

    const code = "{ }";
    const endPosition = matchBracket(code, 0);
    // endPosition = 2

    Complex ex:

    const code =
      "function foo(s: string) {\n" + // <- start pos 24
      "   var str = `text with repeat ${new Array(2).fill(s).map(s=>{ return s + '-{}-' }).join('')} ends here `;\n" +
      "    return { return: str }\n" +
      "}"; // <- return this position 160 (What we need to find!)
    
    const endPosition = matchBracket(code, 24);
    
    // endPosition = 160
    const includeBoth = code.substring(24, 161); // 160+1 to include the end bracket
    const excludeBoth = code.substring(25, 160); // 24+1 to exclude start bracket

    Bracket that can be matchs:

    ${ and $" can only be matched inside string templates (js an cs templates)

    Matching bracket:

    name start end node
    lineComment // \n
    multilineComment /* */
    angle < >
    peparentheses ( )
    square [ ]
    curly { }
    double " "
    single ' '
    jsTemplate ` `
    cSharpTemplate $" "
    escapeJsTemaple ${ } only in jsTemplate
    inCSharpTemaple { } only in cSharpTemplate

    Install

    npm i find-matching-bracket

    DownloadsWeekly Downloads

    14

    Version

    1.0.3

    License

    ISC

    Unpacked Size

    18.9 kB

    Total Files

    6

    Last publish

    Collaborators

    • alfnielsen