Artak  Khachatryan
Artak Khachatryan

Reputation: 311

Javascript reg ex returns only one occurence

I have a string like this

[Key1]+[Key2]+[Key3]

My following regular expression returns [Key1]+[Key2]+[Key3]

var re = new RegExp("\\[.+\\]", "g");
var arr = re.exec("[Key1]+[Key2]+[Key3]");

But I want to get [Key1], [Key2], [Key3]... all the available matches. How can I achive that?

Upvotes: 0

Views: 50

Answers (2)

Toto
Toto

Reputation: 91385

Use the non greedy modifier:

var re = new RegExp("\\[.+?\\]", "g");
//                 here __^

re.exec gives only the first match, if you want all the matches, you have to use string.match(re):

var string = "[Key1]+[Key2]+[Key3]"; 
var re = new RegExp("\\[.+?\\]", "g");
var arr = string.match(re);

then arr contains ["[Key1]", "[Key2]", "[Key3]"]

Upvotes: 3

user2844991
user2844991

Reputation:

var str = "[Key1]+[Key2]+[Key3]"; 
var res = str.match(/\[.+?\]/g);

res contains an array of matches, you can use res.join(",") in order to obtain your string

Upvotes: 1

Related Questions