Skip to content Skip to sidebar Skip to footer

Javascript, Regex - I Need To Grab Each Section Of A String Contained In Brackets

Here's what I need in what I guess must be the right order: The contents of each section of the string contained in square brackets (which each must follow after the rest of the o

Solution 1:

var results = [];
s = s.replace(/\[+(?:(\w+):)?(.*?)\]+/g,
      function(g0, g1, g2){
        results.push([g1, g2.split(',')]);
        return "";
      });

Gives the results:

>> results =
  [["this", [" is", " how"]],
   ["it", [" works", " but", " there"]],
   ["", ["might be bracket", " parts", " without", " colons "]],
   ["", ["nested sections should be ignored?"]]
  ]

>> s = "hi, i'm a string     "

Note it leaves spaces between tokens. Also, you can remove [[]] tokens in an earlier stage by calling s = s.replace(/\[\[.*?\]\]/g, ''); - this code captures them as a normal group.


Post a Comment for "Javascript, Regex - I Need To Grab Each Section Of A String Contained In Brackets"