1

I'm trying to replace a string which is created by a getJSON call. I tried several things inside document ready to replace everything before the :.

Nothing seems to work. Can somebody point me on what I'm doing wrong? If I use replace outside the getJSON then replace should work, right?

 $(document).ready(function(){  
    $.getJSON('url?format=json', function(data){
      var variants = [];
      $.each(data.product.variants, function(index, variant){
        variants.push('<li>'+variant.title+'</li>'); 
        // response is something like "SIZE: XS" or
        // "SIZE: XL" etc...
      });
      variants = variants.join('');  
      $('.size_123').html('<ul>'+variants+'</ul>');
    });
    $(".size_123").html(function(index, currentHtml) {
      return currentHtml.replace(/\SIZE/gi, " ");
    });

   // I also tried this inside the getJSON function. 
   // variantTitle = variant.title;
   // variantClean = variantClean.substr(variantTitle.lastIndexOf(":") + 1);
  });
Meules
  • 1,349
  • 4
  • 24
  • 71
  • couldn't you do `variant.title.replace('SIZE: ','')` in your `each` loop? – Gary Storey Feb 10 '15 at 18:08
  • It will work inside the `.getJSON` callback, but it won't work outside of it. `.getJSON` creates an asynchronous request. You might want to look at http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Stryner Feb 10 '15 at 18:14
  • @GaryStorey: yes tried that too but that doesn't give me the desired result! – Meules Feb 10 '15 at 18:19
  • @Stryner: Yes I've read that yesterday but I really don't have a clue to do that for this piece of code. As I read it there I need to create a new function for such a simple thing like this.... – Meules Feb 10 '15 at 18:20
  • @Meules why doesn't that work? You push the corrected value into the array. `variants.push('
  • '+variant.title.replace('SIZE:','')+'
  • '); `. Maybe I am misunderstanding what you are trying to do? – Gary Storey Feb 10 '15 at 21:11