Search code examples
javascriptjqueryfor-loopsummernote

js for loop keeps looping unlimitedly


I really stuck on this part. firstly, I successfully collected all img sources from summernote editor which user uploads. but when I try to loop them to check if img links encoded to base64 and try to decode them and save them together. but here in my code fo loop keeps looping unlimitedly. Is there some problem with the looping list of img tags?

function getAllImages() {
let images = $(".note-editable p").find('img').map(function() {
      return $(this).attr('src')
    }).get();
console.logt(images);
 let base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
 let imgSrc = [];
   for(let i=0; images.length; i++){
     if(base64regex.test(images[i])) {
        console.log("["+images[i]+"]");
        let decoded=atob(images[i]);
        console.log("img decoded");
        imgSrc.push(decoded);
     } 
     else if(base64regex.test(images[i]) == false){

        console.log("["+images[i]+"]");
        imgSrc.push(images[i]);
     }      
 }
  return imgSrc;
 }

Solution

  • Please use i < images.length in the for loop.

    function getAllImages() {
    let images = $(".note-editable p").find('img').map(function() {
          return $(this).attr('src')
        }).get();
    console.logt(images);
     let base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
     let imgSrc = [];
       for(let i=0; i < images.length; i++){
         if(base64regex.test(images[i])) {
            console.log("["+images[i]+"]");
            let decoded=atob(images[i]);
            console.log("img decoded");
            imgSrc.push(decoded);
         } 
         else if(base64regex.test(images[i]) == false){
    
            console.log("["+images[i]+"]");
            imgSrc.push(images[i]);
         }      
     }
      return imgSrc;
     }