{
function findMatchingParenthesis(str, index) {
let openParens = 0;
for (let i = index; i < str.length; i++) {
if (str[i] === "(") {
openParens++;
} else if (str[i] === ")") {
openParens--;
if (openParens === 0) {
return i;
}
}
}
return -1;
}
function replaceNestedBracePattern(str) {
let result = "";
let i = 0;
while (i < str.length) {
if (str.slice(i, i + 9) === "_brace.b_") {
const openingParenthesisIndex = str.lastIndexOf("(", i);
const closingParenthesisIndex = findMatchingParenthesis(
str,
openingParenthesisIndex
);
if (closingParenthesisIndex !== -1) {
const anythingX = str.slice(
openingParenthesisIndex + 1,
closingParenthesisIndex
);
i = closingParenthesisIndex + 1;
const openingParenthesisIndexY = str.indexOf("(", i + 8);
const closingParenthesisIndexY = findMatchingParenthesis(
str,
openingParenthesisIndexY
);
if (closingParenthesisIndexY !== -1) {
const anythingY = str.slice(
openingParenthesisIndexY + 1,
closingParenthesisIndexY
);
result =
result.slice(0, openingParenthesisIndex) +
`underbrace(${anythingX},${anythingY})`;
i = closingParenthesisIndexY + 1;
} else {
result += str.slice(i, i + 9);
i += 9;
}
} else {
result += str.slice(i, i + 9);
i += 9;
}
} else {
result += str[i];
i++;
}
}
return result;
}
const input = '(b dot.op b dots.h.c b)_brace.b_(k_1 upright(" mal"))';
const output = replaceNestedBracePattern(input);
return output;
}