Javascript - return string between square brackets

javascript, regex, string

Solution

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];
}

Problem

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.

Original source