Skip to content
Advertisement

Javascript Regex – Get All string that has square brackets []

I have string data below:

var data = "somestring[a=0]what[b-c=twelve]----[def=one-2]test"

I need to get all strings that contain square brackets []. This is the result that I want.

["[a=0]", "[b-c=twelve]", "[def=one-2]"]

I’ve tried using regex /[(.*?)]/, but what I’ve got is an only the first array element is correct, the next elements are basically the same value but without the square brackets.

data.match(/[(.*?)]/);
// result => ["[a=0]", "a=0"]

What regexp should I use to achieve the result that I want? Thank you in advance.

Advertisement

Answer

You want to use the g (global) modifier to find all matches. Since the brackets are included in the match result you don’t need to use a capturing group and I used negation instead to eliminate the amount of backtracking.

someVar.match(/[[^]]*]/g);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement