Match balanced character pairs, like "{" and "}"
npm install @isaacs/balanced-matchA hybrid CJS/ESM TypeScript fork of
balanced-match.
Match balanced string pairs, like { and } or and . Supports regular expressions as well!


Get the first matching pair of braces:
``js
import { balanced } from '@isaacs/balanced-match'
console.log(balanced('{', '}', 'pre{in{nested}}post'))
console.log(balanced('{', '}', 'pre{first}between{second}post'))
console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post'))
`
The matches are:
`bash`
$ node example.js
{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' }
{ start: 3,
end: 9,
pre: 'pre',
body: 'first',
post: 'between{second}post' }
{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' }
For the first non-nested matching pair of a and b in str, return an
object with those keys:
- start the index of the first match of ab
- end the index of the matching a
- pre the preamble, and b not includeda
- body the match, and b not includeda
- post the postscript, and b not included
If there's no match, undefined will be returned.
If the str contains more a than b / there are unmatched pairs, the first match that was closed will be used. For example, {{a} will match ['{', 'a', ''] and {a}} will match ['', 'a', '}'].
For the first non-nested matching pair of a and b in str, return an[ , ]
array with indexes: .
If there's no match, undefined will be returned.
If the str contains more a than b / there are unmatched pairs, the first match that was closed will be used. For example, {{a} will match [ 1, 3 ] and {a}} will match [0, 2]`.