-2

I have a string

var str = "{{a}} {{b}} aaa";

I want to split the string with {{}}. So, my expected result is

array = ["a", "b"]

Update:

As another case, given

var str1 = "{{a {{b}}}}",
    str2 = "{{{a}}}";

The result should be

var arr1 = ["b"],
    arr2 = ["a"];
Vu Le Anh
  • 708
  • 2
  • 8
  • 21

2 Answers2

3

One option would be to match them all, then extract the contents.

var units = [
    "{{a}} {{b}} aaa",
    "{{a {{b}}}}",
    "{{{a}}};"
];
units.forEach(function(str) {
    var matched = str.match(/{{([^}]*[^{]*)}}/g).map(function(s) {
        return s.substring(2, s.length - 2)
    });
    console.log(str, '=');
    console.log(matched);
});
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
0

As mentioned there might not be a best way to cover every scenario, but split could be used like:

var str1 = "{{a}} {{b}} aaa", str2 = "{{a {{b}}}}", str3 = "{{{a}}};"

var splits = str1.split(/[^{][^.][^}]|[{}]/).filter(Boolean);
console.log(splits);

Results:

Array [ "a", "b" ]
Array [ "b" ]
Array [ "a" ]

Examples:

https://jsfiddle.net/gsL46bg7

l'L'l
  • 44,951
  • 10
  • 95
  • 146