Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - return string between square brackets

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.

like image 227
BrynJ Avatar asked Sep 29 '09 14:09

BrynJ


2 Answers

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];
}
like image 100
Alex Barrett Avatar answered Nov 01 '22 01:11

Alex Barrett


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, '' );
like image 18
Stephen Sorensen Avatar answered Nov 01 '22 00:11

Stephen Sorensen