I need to return just the text contained within square brackets in a string. I have the following regex, but this also returns the square brackets:
var matched = mystring.match("\\[.*]");
A string will only ever contain one set of square brackets, e.g.:
Some text with [some important info]
I want matched to contain 'some important info', rather than the '[some important info]' I currently get.
Use grouping. I've added a ?
to make the matching "ungreedy", as this is probably what you want.
var matches = mystring.match(/\[(.*?)\]/);
if (matches) {
var submatch = matches[1];
}
Since javascript doesn't support captures, you have to hack around it. Consider this alternative which takes the opposite approach. Rather that capture what is inside the brackets, remove what's outside of them. Since there will only ever be one set of brackets, it should work just fine. I usually use this technique for stripping leading and trailing whitespace.
mystring.replace( /(^.*\[|\].*$)/g, '' );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With