Replace text in square brackets

var a = "[i] earned [c] coin for [b] bonus"; 

How to get the string "__ earned __ coins for __ bonus" from the above variable in JavaScript?

All I want to do is replace all the brackets [] and its contents with __ .

+6
source share
3 answers
 a = a.replace(/\[.*?\]/g, '__'); 

If you expect new lines to appear, you can use:

 a = a.replace(/\[[^\]]*?\]/g, '__'); 
+7
source
 a = a.replace(/\[[^\]]+\]/g, '__'); 

jsFiddle .

+3
source

Here's a fun example of matching groups.

 var text = "[i] italic [u] underline [b] bold"; document.body.innerHTML = text.replace(/\[([^\]]+)\]/g, '(<$1>$1</$1>)'); 

Structure

 / // 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
source

Source: https://habr.com/ru/post/888889/


All Articles