var a = "[i] earned [c] coin for [b] bonus";
How to get string "__ earned __ coin for __ bonus" from the variable above in JavaScript?
All I want to do is to replace all the bracket []
and its content to __
.
a = a.replace(/\[.*?\]/g, '__');
if you expect newlines to be possible, you can use:
a = a.replace(/\[[^\]]*?\]/g, '__');
a = a.replace(/\[[^\]]+\]/g, '__');
jsFiddle .
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>)');
/ // 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.