0

Let's consider we have a string named str, which is defined as :

var str = "I want to replace( this & ( this ) )"

Now, I did something like this :

str = str.replace(/replace\((.*?)\)/gm, function(_, a) {
  console.log("Replacing : " + a)
  return "it !"
}

Output :

// In Console
Replacing : this & ( this
// Returned
I want to it ! )

But, I wanted the output as :

// In Console
Replacing : this & ( this )
// In Return
I want it !

I heard about the Balanced Parenthesis Algorithm. Therefore can this help me to solve this task ? If yes, how ? What if, there are more brackets in the string ? If no, how can this be done ?

Arcanadian Arc
  • 1,202
  • 2
  • 17

1 Answers1

1

const str = "I want to replace ( this & ( this ) )"

const withoutPlaceholder = [str.split('to replace')[0], 'it!'].join('')
// output: I want it!

const withoutAllParenthesis = str.split(/\(([^)]+)\)/)
  .find(strPart => !strPart.includes('(') && !strPart.includes(')')) + ' it!'
// output: I want to replace it!

const balancedParenthesis = XRegExp.matchRecursive(str, '\\(', '\\)', 'g')[0]
const withoutBalancedParenthesis = str.split(balancedParenthesis).join('it!')
// output: I want to replace (it!)

console.log(withoutPlaceholder)
console.log(withoutAllParenthesis)
console.log(withoutBalancedParenthesis)
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.2.0/xregexp-all.js"></script>

related questions and answers: - Regular expression to match balanced parentheses

AndreasT
  • 776
  • 5
  • 12