Reputation: 47
I am using Regex with JavaScript and want to return the content within the square brackets (including the brackets themselves) in the following string:
var str = '##abde[fgh]ijk[mn]op';
var brackets = str.match(/\[.{1,}\]/g); //["[fgh]ijk[mn]"]
I wanted brackets
to return ["[fgh]", "[mn]"]
, rather than the content (ijk)
outside of the brackets. How can this be fixed? Thank you.
Upvotes: 1
Views: 82
Reputation: 5237
The problem here is that .
matches any character (including square brackets).
You can use a character class like:
[^\]]
to match any character except square brackets.
So this should work for you:
str.match(/\[[^\]]{1,}\]/g);
Better would be this:
str.match(/\[[^\]]+\]/g);
It's a little neater since {1,}
is semantically equivalent to +
.
Upvotes: 2