Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all values between '[ ]' on a string with JavaScript [closed]

How are you guys doing? I'd like to ask today if you could help me with a tricky question that I was unable to solve on my own.

I [have] strings that [are] like this.

I was looking for a way to get "have" and "are" and form an array with them using JavaScript. Please notice that this is an example. Sometimes I have several substrings between braces, sometimes I don't have braces at all on my strings. My attempts focused mostly on using .split method and regex to accomplish it, but the closest I got to success was being able to extract the first value only.

Would any of you be so kind and lend me an aid on that?

I tried using the following.

.split(/[[]]/);
like image 431
YLeven Avatar asked Mar 16 '26 11:03

YLeven


1 Answers

You can use the exec() method in a loop, pushing the match result of the captured group to the results array. If the string has no square brackets, you will get an empty matches array [] returned.

var str = 'I [have] strings that [are] like this.'
var re  = /\[([^\]]*)]/g, 
matches = [];

while (m = re.exec(str)) {
  matches.push(m[1]);
}
console.log(matches) //=> [ 'have', 'are' ]

Note: This will only work correctly if the brackets are balanced, will not perform on nested brackets.

like image 177
hwnd Avatar answered Mar 19 '26 01:03

hwnd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!