String view:

var str = "some text [[[[test 1]] test 2]] other text"; 

How to remove everything in square brackets, including the brackets themselves?

My decision:

 new_str = str.replace(/\[.*\]\].*\]\]/gi,""); 

Doesn't quite fit, what's wrong?

updated as advised:

 var str = "some text [[[[test 1]] test 2]] other text"; new_str = str.replace(/\[\[(.)+\[\[(.)+\]\] \]\]/i,''); alert(new_str); 

As a result, the entire line returns.

fiddle test

    2 answers 2

    Well, you have only one open bracket on the left, and there are two.

     REGEX: #\[\[(.)+\[\[(.)+\]\] \]\]#i 

    Should work.

    Or + replace with * if there may be no characters.

    For the first example it works, and this is for the second:

     /\[\[\[\[(.)+\]\](.)+\]\]/gi 

    Your code:

     var str = "some text [[[[test 1]] test 2]] other text"; new_str = str.replace(/\[\[\[\[(.)+\]\](.)+\]\]/gi,''); alert(new_str); 

    You can even like this:

     /\[.*\]/gi 
    • the fact is that there may even be line breaks. - Smash
    • Add the g modifier and the face characters at the beginning and at the end of the regular expression. - Gena Ant
    • Nope, did not help g - Smash
    • one
      Yes, I feel, once again I apologize, I wrote it by hand. - Smash

    It depends on what you need. for example

     str = str.replace(/\[\[.*\]\]/gm, ""); 

    As @GenchiK correctly noted in the comments, you may just need

     str = str.replace(/\[.*\]/gm, ""); 

    if the brackets are not necessarily double.


    To avoid problems with the translation of lines, note that the dot does not match the line break . So what you need is this :

     str = str.replace(/\[[\s\S]*\]/gm, ""); 
    • Invalid expression. - Gena Ant
    • @GenchiK: can you argue? The syntax is correct, see link. Copes with the task, see link. No additional requirements of the vehicle did not make. - VladD
    • And what is there to argue? Run and see! - Gene Ant
    • one
      @GenchiK: Thank you! Since the vehicle does not say what it is he needs, perhaps a more specific expression is more correct. - VladD
    • one
      @Maris: see the answer update. - VladD