0

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]

5 Answers 5

4

Use modifier /g

And also escape the ] inside the character class []

regex = /\[[^\]]*\]/g;
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, this worked. Is there a way to only return the strings within the brackets? I'm looking specifically for an array with [parent,0,child].
regex = /\[([^\]]*)\]/g;
@JoeFrambach - That regex value still returns the [] in the results. match.forEach(function(key){ console.log(key); }) returns ['[parent]','[0]','[child]'], I'm looking for ['parent','0','child'] as the results set.
@Axel Javscript doesn't support lookbehind. Otherwise it could be very easy for this. You can use Positive lookahead to check ] at right side, and keeping left side open as Jerry posted a solution below. Alternately, if your input is same like the example, you can use .split(/[\]\[]+/) for this purpose.
2

An alternative path to your end goal:

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

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

3 Comments

You could replace .filter(function(s){return !!s}) with filter(Boolean)
Ah yes! That's brilliant
Nice solution, and a lot cleaner! Exactly the results I was going for.
2

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) })

Comments

1

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.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.