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 __
.
我想要做的就是将所有的括号[]及其内容替换为__。
3 个解决方案
#1
7
a = a.replace(/\[.*?\]/g, '__');
if you expect newlines to be possible, you can use:
如果您希望换行符可以使用,您可以使用:
a = a.replace(/\[[^\]]*?\]/g, '__');
#3
1
Here is a fun example of matching groups.
以下是匹配组的有趣示例。
var text = "[i] italic [u] underline [b] bold";
document.body.innerHTML = text.replace(/\[([^\]]+)\]/g, '(<$1>$1</$1>)');
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
#1
7
a = a.replace(/\[.*?\]/g, '__');
if you expect newlines to be possible, you can use:
如果您希望换行符可以使用,您可以使用:
a = a.replace(/\[[^\]]*?\]/g, '__');
#2
#3
1
Here is a fun example of matching groups.
以下是匹配组的有趣示例。
var text = "[i] italic [u] underline [b] bold";
document.body.innerHTML = text.replace(/\[([^\]]+)\]/g, '(<$1>$1</$1>)');
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