Home > Back-end >  Regex replacing between brackets that contain the same type of bracket in between
Regex replacing between brackets that contain the same type of bracket in between

Time:11-03

I am trying to replace the following string

\section{Welcome to $\mathbb{R}^n$}

with

<h1>Welcome to $\mathbb{R}^n$</h1>

Obviously, the problem is that I have opening { and } between the curly brackets themselves. I have tried to use something like

strOutput = strOutput.replace(/\\section\*\s*\{([^}]*)\}/g, "<h1>$1</h1>");

in JavaScript, but with no luck. How do I go on approaching this?

CodePudding user response:

Here is an example:

let str = String.raw`\section{Welcome to $\mathbb{R}^n$}`

let result = `<h1>${str.match(/(?<={).*(?=})/)}</h1>`

console.log(result)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

How about this:

let str = String.raw`\section{Welcome to $\mathbb{R}^n$}`
let m = str.replace(/\\section\s*\{(.*)}$/g, "$1")
let result = `<h1>${m}</h1>`

console.log(result)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

The problem with your expression was \*, which means a literal asterisks, but otherwise you nearly had it!

  • Related