Meules Meules - 1 month ago 6x
Javascript Question

Loop through getJson result

I'm having trouble to loop through returned JSON result. If the result matches some requirements then append them to a

element. Yes I'm still learning :)

The returned result looks like this
[text][text2][text3]bla,blabla, blabla
I want only to grab the elements between brackets. Afterwards these brackets need to be removed and the cleaned result should be placed in a

So what I have is this:

$.getJSON('some-url?format=json', function(e) {

var keywords =; //result = [text][text2][text3]bla,blabla, blabla

$(keywords).each(function(i, keys) {
var keys = keywords.match(/\[(.*?)\]/); //matches if text is between brackets

if (keys) {
var submatch = keys[1];

$('.some-div ul').html('<li>'+submatch+'</li>');


Doing it like above gives me an error
Error: Syntax error, unrecognized expression: [text][text2][text3]

What I'm I doing wrong?

Cam Cam

Presuming that is a string you wish to perform a regular expression upon, simply use JavaScript's regex String#match function and loop over the result using Array#forEach:

$.getJSON('some-url?format=json', function(e) {
  // if is string "[text][text2][text3]bla,blabla, blabla"
  // perform a regex match on the string...  and loop over using forEach
  var result =\[([^\]]+)\]/g);
  if( result ) {
      // since we're dealing with the entire match rather than match group 1
      // we'll want to chop off the first "[" and last char "]" via substring
      $('.some-div ul').append('<li>'+text.substring(1,text.length-1)+'</li>');
      // also: use append rather than html to avoid overwriting previous li elements

The above will output:


Which you can test independent of your AJAX call:

"[text][text2][text3]bla,blabla, blabla".match(/\[([^\]]+)\]/g).forEach(function(text){