Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

remove square brackets and it content from string in javascript

How to remove characters between two brackets and brackets. For example

Let it [Am]be, let it [C/G]be, let it [F]be, let it [C]be
[C]Whisper words of [G]wisdom, let it [F]be [C/E] [Dm] [C]

I want above string to

Let it be, let it be, let it be, let it be
Whisper words of wisdom, let it be  

I use this regx but it is only take out brackets.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var reg = /[\[\]']+/g
var x = song.replace(reg,"")
console.log(x);

>Solution :

You need to escape the outer [] so you’re matching those literally, and allow anything except a ] inside. So:

var reg = /\[[^\]]*\]/g;

Here’s a breakdown (also on regex101):

  • \[ matches [ literally
  • [^\]] matches any character that isn’t a ]
  • * says "zero or more" of those (so it replaces []; if you don’t want that, change this to + for "one or more")
  • \] matches ] literally (I probably don’t need to escape it there, but I tend to anyway)

Live Example:

const song = `Let it [Am]be, let it [C/G]be, let it [F]be, let it [C]be
[C]Whisper words of [G]wisdom, let it [F]be [C/E] [Dm] [C]`;

var reg = /\[[^\]]*\]/g;
var x = song.replace(reg,"");
console.log(x);

Side note: In modern JavaScript, we don’t use var. Use let or const instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading