gpt4 book ai didi

javascript - 如何使用平衡括号算法替换 JavaScript 字符串中的单词?

转载 作者:行者123 更新时间:2023-12-02 21:41:38 25 4
gpt4 key购买 nike

假设我们有一个名为 str 的字符串,其定义为:

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

现在,我做了这样的事情:

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

输出:

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

但是,我希望输出为:

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

我听说过平衡括号算法。那么这可以帮助我解决这个任务吗?如果是,怎么办?如果字符串中有更多括号怎么办?如果不是,如何做到这一点?

最佳答案

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>

相关问题及解答:-Regular expression to match balanced parentheses

关于javascript - 如何使用平衡括号算法替换 JavaScript 字符串中的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60353398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com