Meules Meules - 3 months ago 7
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

<li>
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
<li>
element.

So what I have is this:

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

var keywords = e.shop.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
Answer

Presuming that e.shop.keywords 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 e.shop.keywords is string "[text][text2][text3]bla,blabla, blabla"
  // perform a regex match on the string...  and loop over using forEach
  var result = e.shop.keywords.match(/\[([^\]]+)\]/g);
  if( result ) {
    result.forEach(function(text){
      // 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:

<li>text</li>
<li>text2</li>
<li>text3</li>

Which you can test independent of your AJAX call:

"[text][text2][text3]bla,blabla, blabla".match(/\[([^\]]+)\]/g).forEach(function(text){
  console.log('<li>'+text.substring(1,text.length-1)+'</li>');
});
Comments