javascript 替换方括号内的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6108555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:29:44 来源:igfitidea点击:
Replace text inside of square brackets
提问by theHack
var a = "[i] earned [c] coin for [b] bonus";
How to get string "__ earned __ coin for __ bonus" from the variable above in JavaScript?
如何在 JavaScript 中从上面的变量中获取字符串“__ 获得 __ 硬币以获得 __ 奖金”?
All I want to do is to replace all the bracket []
and its content to __
.
我想要做的就是将所有括号[]
及其内容替换为__
.
回答by Brett Zamir
a = a.replace(/\[.*?\]/g, '__');
if you expect newlines to be possible, you can use:
如果您希望可以使用换行符,则可以使用:
a = a.replace(/\[[^\]]*?\]/g, '__');
回答by Mr. Polywhirl
Here is a fun example of matching groups.
这是匹配组的有趣示例。
var text = "[i] italic [u] underline [b] bold";
document.body.innerHTML = text.replace(/\[([^\]]+)\]/g, '(<></>)');
Breakdown
分解
/ // BEGIN pattern
\[ // FIND left bracket (literal) '['
( // BEGIN capture group 1
[ // BEGIN character class
^ // MATCH start anchor OR
\] // MATCH right bracket (literal) ']'
] // END character class
+ // REPEAT 1 or more
) // END capture group 1
\] // MATCH right bracket (literal) ']'
/ // END pattern
g // FLAG global search