Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
160
rated 0 times [  163] [ 3]  / answers: 1 / hits: 110398  / 15 Years ago, tue, september 29, 2009, 12:00:00

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.


More From » regex

 Answers
4

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

[#98600] Thursday, September 24, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daryldeontaeh

Total Points: 46
Total Questions: 97
Total Answers: 105

Location: Maldives
Member since Sat, Jan 29, 2022
2 Years ago
;