Axel
Axel

Reputation: 10772

Matching and returning all strings contained within [] using regex in javascript

I'm wanting to match all values contained within [] brackets using regex in javascript.

I have the following string: [parent][0][child]

Attempting to use the regex value: \[[^]]*\]

Entering both values into the Rexex Tester matches everything successfully, however when I actually implement it, match only returns one array key value.

JS Code:

var string = '[parent][0][child]';
regex = /\[[^]]*\]/;
match = string.match(regex);  //Returns just [0]?

I'm wanting match to return an array with all the matching values [parent, 0, child]

Upvotes: 0

Views: 114

Answers (5)

Amit Joki
Amit Joki

Reputation: 59232

You can use this regex:

/[^[\[\]]+/g

Use it like this:

var string = '[parent][0][child]';
var regex = /[^[\[\]]+/g;
var matches = string.match(regex);
console.log(matches); //[parent,0,child]

Upvotes: 0

000
000

Reputation: 27247

An alternative path to your end goal:

var str = "[parent][0][child]"
str.split(/\[|\]/).filter(Boolean)

outputs ["parent", "0", "child"]

Upvotes: 2

Jerry
Jerry

Reputation: 71538

You could use a lookahead and nothing else to help get only the parts within the square brackets; assuming that you are 100% sure the strings have balanced square brackets:

regex = /[^\[\]]*(?=\])/g;

regex101 demo

The g flag is the global flag to match all the possible matches.

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382150

Use the g flag to get more than one result and fix your regex :

regex = /\[[^\]]*\]/g;

If you want to get only the part between brackets without explicit iteration, you may do

var matches = string.match(regex).map(function(v){ return v.slice(1,-1) })

Upvotes: 2

Sabuj Hassan
Sabuj Hassan

Reputation: 39365

Use modifier /g

And also escape the ] inside the character class []

regex = /\[[^\]]*\]/g;

Upvotes: 4

Related Questions