How do i get all images from a iframe

I want to get all images from a iframe and turn it into a array to get it src

var iframe = document.getElementById('iframeId');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

var images = innerDoc.getElementsByTagName("img").innerHTML;
document.getElementById("inv").innerHTML = document.getElementById("inv").innerHTML + "<br>"+ images[0].src;

Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame. at update (file:///H:/images.html:56:63)

Count the number of links and divide them in 3 groups

I am developing a webpage for myself where I am fetching links to tutorials using a API. The problem is, there are lots of links to click on.

Is there any way in JavaScript to divide the links in 3 groups and have 3 buttons where on click they open all the links in group? Like, “Open First 1/3”, “Open Second 1/3” and “Open Last 1/3”?

I tried to divide the links.length with 3, but it gives me a the result in decimal, like when the links count is 31, I am getting 10.3333333333.

I am really clueless here. Any help will be appreciated. I know this question sounds kind of Do It For Me type, but believe me, its not. Just guiding me to the proper direction would be enough.

Thanks

How to add onClick event in a button within a modal?

I have a function that displays a modal called ‘ShopModal’. within this modal, I have a button called petDetailsButton which I would like to check if its onClick function works but when I wrote console.log on the onClick() function it does not display the message on the console.

I tried using alert to notify if the button is clicked but it still doesn’t work.

Here is a code snippet of my function below:

async function GetAllShopData() {

            const querySnapshot = await getDocs(collection(db,"Shop"));
            const querySnapshot2 = await getDocs(collection(db,"User"));
            const petQuerySnapshot = await getDocs(query(collection(db, "Pet"), where("displayFor", "==", "forSale")));
            const serviceQuerySnapshot = await getDocs(collection(db,"Services"));

            var shopCloseBtn = document.getElementById("shopCloseModalBtn");
            var modal = document.getElementById("shopModal");
            const span = document.getElementById("shop-span");

                const petModal = document.getElementById("petDetailsModal");

                var petForSale = document.getElementById("petsForSaleLabel");
                
                const table = document.getElementById("shopTableBody");

                var data = [];

                querySnapshot.forEach(doc => {

                    const ownerIdNo = doc.data().breeder;
                    const shopName = doc.data().shopName;

                    let idNo = "";
                    let gender = "";
                    let birthday = "";
                    let address = "";
                        
                    let firstName = "";
                    let middleName = "";
                    let lastName = "";
                    let fullName = "";

                    let role = "";
                    let status = "";

                    let petName = "";
                    let petBreed = "";

                    let serviceName = "";

                    let petArr = [];

                    let servArr = [];

                    querySnapshot2.forEach(doc => {

                        if (ownerIdNo === doc.data().idNo){
                        
                            idNo = doc.data().idNo;
                            gender = doc.data().gender;
                            birthday = doc.data().birth;
                            address = doc.data().address;

                            firstName = doc.data().firstName;
                            middleName = doc.data().middleName;
                            lastName = doc.data().lastName;
                            fullName = [firstName, middleName, lastName].filter(Boolean).join(" ");

                            role = doc.data().role.join(", ");
                            status = doc.data().status;
                            
                            }

                        });

                    
                    petQuerySnapshot.forEach(doc => {
                        if(ownerIdNo === doc.data().pet_breeder){
                            const petDetailsButton = document.createElement("button");
                            petDetailsButton.innerHTML = '<i class="fa fa-eye" aria-hidden="true"></i>';
                            petDetailsButton.style.marginRight = "5px";
                            petDetailsButton.style.border = "0";
                            petDetailsButton.style.background = "transparent";
                        
                            petDetailsButton.onclick = async function() {

                           console.log("clicked!") //does not display in console
                            }

                            const petArrItem = ` · ${doc.data().pet_name} - ${doc.data().pet_breed} ${petDetailsButton.outerHTML} ${'<br>'}`;
                            petArr += petArrItem;
                        }
                    });             

                    serviceQuerySnapshot.forEach(doc => {
                        
                        if(ownerIdNo === doc.data().shooter_id){
                            const servViewButton = document.createElement("button");
                            servViewButton.innerHTML = '<i class="fa fa-eye" aria-hidden="true"></i>';
                            servViewButton.style.marginRight = "5px";
                            servViewButton.style.border = "0";
                            servViewButton.style.background = "transparent";

                            servViewButton.onclick = async function() {

                                

                            }

                            const servArrItem = ` · ${doc.data().name} ${servViewButton.outerHTML} ${'<br>'}`;
                            servArr += servArrItem;
        
                        }

                    });

                    const row = table.insertRow();

                    const ownerIdCell = row.insertCell();
                    ownerIdCell.innerText = ownerIdNo;

                    const shopNameCell = row.insertCell();
                    shopNameCell.innerText = shopName;

                    const statusCell = row.insertCell();
                    statusCell.innerText = status;

                    const actionCell = row.insertCell();

                    const editButton = document.createElement("button");
                    editButton.className = "editBtn";
                    editButton.innerHTML = '<i class="fa-solid fa-pen-to-square"></i>';
                    editButton.style.marginRight = "5px";

                    editButton.onclick = async function() {
                        modal.style.display = "block";

                        shopIdNoLabel.innerText = idNo;
                        shopFirstNameLabel.innerText = firstName;
                        shopMiddleNameLabel.innerText = middleName;
                        shopLastNameLabel.innerText = lastName;
                        shopGenderLabel.innerText = gender;
                        shopBirthdayLabel.innerText = birthday;

                        shopRoleLabel.innerText = role;

                        shopStatusLabel.innerText = status;
                        
                        petsForSaleLabel.innerHTML = petArr;
                        serviceOfferedLabel.innerHTML = servArr;
                    }
                    
                    span.onclick = function() {
                    modal.style.display = "none";
                    }

                    shopCloseBtn.onclick = function() {
                        modal.style.display = "none";
                    }

                    actionCell.appendChild(editButton);

                    const deleteButton = document.createElement("button");
                    deleteButton.className = "deleteBtn";
                    deleteButton.innerHTML = '<i class="fa-regular fa-trash-can"></i>';
                    
                    deleteButton.onclick = async function() {
                    try {
                        window.confirm("Are you sure you want to delete this document?");
                        if(confirm == true)
                        {
                            await deleteDoc(doc.ref);
                            window.alert("Document successfully deleted!");
                            const row = deleteButton.closest("tr");
                            row.remove();
                        }
                    } catch (error) {
                        console.error("Error removing document: ", error);
                    }
                    };

                    actionCell.appendChild(deleteButton);

                });

                AddAllItemsToTable(data);
        }

TypeError when running expo go

I’m getting this error in the terminal when trying to run a fresh project in expo go, I don’t know what’s causing it since the project is fresh.
This is the full error

TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["Exponent-Server"]

Note that after installing expo environment for the first time everything was fine, I started a project I ran it without any problems and I still can run it.

Mouse over events in d3 not being called in a small multiple

I am trying to create a tooltip mouseover event for a small multiple graph in d3 but the mouseover event is never triggered (the response function is just a console.log() call at this stage).

I generate the small multiple as such

 let svg = d3.select("#vis")
                    .selectAll("uniqueChart")
                    .data(year_dat)
                    .enter()
                    .append('svg')
                    .attr('width', 700)
                    .attr('height', 450)
                    .attr('opacity', 1)

and then append lines to the object (after adding axes etc) svg as so

svg
    .append("path")
    
    .attr("fill", "none")
    .attr("stroke", linecol)
    .attr("stroke-width", 3)
    .attr('class', 'lines')
    .attr('pointer-events', 'all')
    .attr("d", function(d) { return d3.line()
      .x(function(d) { return timex(d.hour) })
      .y(function(d) { return timey(d.med_est/60) })
      (d.values)
      })
    .on('mouseover', mouseOver)
    .on('mouseout', mouseOut)

But although the plot forms correctly there is never a mouseover event to call the mouseOver function (as mentioned it is just a console.log() at this stage. I suspect it is something to do with the nesting of the data and the multiple plots but there’s no error messages.

Below is a shortened version of the code so far that results in this behaviour (or lack thereof)

let dataset, svg, map

let allGroup
var timey, yAxis
var col, linecol



const margin = {left: 170, top: 30, bottom: 30, right: 20}
const width = 700 - margin.left - margin.right
const height = 400 - margin.top - margin.bottom
const colours = {
 Sydney : "#87ceeb",
 Melbourne : "#000080",
 Brisbane : "#800000",
 Adelaide : "#dc0014",
 Perth : "#fecb29"
}
let rn = "M5_Sydney"
//Read Data, convert numerical categories into floats
//Create the initial visualisation


d3.csv('data/19-22_times.csv', function(d){
    return {
        hour: +d.hour,
        LQ_est: +d.LQ_est,
        med_est: +d.med_est,
        UQ_est: +d.UQ_est,
        LQ_est_char: d.LQ_est_char,
        med_est_char: d.med_est_char,
        UQ_est_char: d.UQ_est_char,
        n_obvs: +d.n_obvs,
        bd_label: d.bd_label,
        route_name: d.route_name,
        year: +d.year,
        city: d.city,
        short_name: d.short_name
        
    };
}).then(data => {
    time_dat = data
    allGroup = [...new Set(time_dat.map(d => d.short_name))]
    //console.log(time_dat)
    r_dat = time_dat.filter(function(d){return d.short_name == rn})
 
    
    d3.select("#selectButton")
      .selectAll('myOptions')
        .data(allGroup)
      .enter()
    .append('option')
    .text(d => d)
    .attr('value', d => d)
    .property('selected', function(d){
        return d == "M5_Sydney"
    });
    createScales()
    setTimeout(drawInitial(), 100)
    
})

 




function createScales(){
  
    

    let min_time, max_time
    min_time = d3.min(r_dat, function(d) { return d.UQ_est; })/60 //remember UQ is upper quartile of speeds
    max_time = d3.max(r_dat, function(d) { return d.LQ_est; })/60
    console.log(min_time)
  
    console.log(max_time)

    timex = d3.scaleLinear(domain = [0, 23], [70, width+150])
    timey = d3.scaleLinear(domain = [0, 1.1*max_time], [height, 0+margin.top])
    console.log(timey)
   
}





// All the initial elements should be create in the drawInitial function
// As they are required, their attributes can be modified
// They can be shown or hidden using their 'opacity' attribute
// Each element should also have an associated class name for easy reference



function drawInitial(){



    let year_dat_ =r_dat.filter(function(d){return d.year == 2019})
    year_dat = d3.nest()
        .key(function(d) {return d.route_name})
        .entries(year_dat_)

    let svg = d3.select("#vis")
                    .selectAll("uniqueChart")
                    .data(year_dat)
                    .enter()
                    .append('svg')
                    .attr('width', 700)
                    .attr('height', 450)
                    .attr('opacity', 1)

                    //.style('background', 'beige')


    let xlabels = ['0:00', '4:00', '8:00', '12:00', '16:00', '20:00'];            
    svg.append('g')
    .call(d3.axisBottom(timex)
        .ticks(6)
        .tickValues([0, 4, 8, 12, 16, 20])
        .tickFormat((d,i) => xlabels[i])
        )
    .attr("transform", "translate(0," + height + ")")
    .style('font-size', '20px')
    .style('font-family', "Crimson Text")
    .select(".domain")
    .attr('opacity', 0)
    .attr('id', 'xaxis')

    yAxis = d3.axisRight(timey).ticks(4)
    
   svg.append('g')
    .attr('id', 'yaxis')
    .attr('class', 'yaxis')
    .style('font-size', '20px')
    .style('font-family', "Crimson Text")
    .call(yAxis)
    .select(".domain")
    .attr('opacity', 0)
    


   let col = colours[r_dat[0]["city"]]
   //console.log(col)
   let linecol = "black"


   console.log(rn)
   svg
      .append("path")
      .attr("fill", col)
      .attr("stroke", col)
      .attr("stroke-width", 1.5)

      .attr('class', 'bands')
      .attr("d", function(d) { return d3.area()
        .x(function(d) { return timex(d.hour) })
        .y0(function(d) { return timey(d.UQ_est/60) })
        .y1(function(d) { return timey(d.LQ_est/60) })
        (d.values)
        })
      .on('mouseover', mouseOver)
      
    svg
    .append("path")
    
    .attr("fill", "none")
    .attr("stroke", linecol)
    .attr("stroke-width", 3)
    .attr('class', 'lines')
    .attr('pointer-events', 'all')
    .attr("d", function(d) { return d3.line()
      .x(function(d) { return timex(d.hour) })
      .y(function(d) { return timey(d.med_est/60) })
      (d.values)
      })
    .on('mouseover', mouseOver)
   
    


    svg
      .append("text")
      .attr("x", width/2)
      .attr("y", margin.top)
      .attr('class', 'title')
        .attr("text-anchor", "middle")  
        .style("font-size", "30px") 
        //.style("text-decoration", "underline")  
        .text(function(d){ return(d.key)})

       
      
    
     
   
    
   
   
}

 function mouseOver(d, i){

      console.log('MOUSE OVER TIGGERED')  
    }

NEXTJS getStaticProps generates static Json data on page, how is that SEO friendly?

NEXTJS getStaticProps passes your data to the page at build time, generates static Json data on page.

It is up to the page React to compose the data into components. So SEO would not see the actual list of HTML Data directly right? how is that SEO-friendly?

I mean for example, your page has:

/* static data list given by static page */
const data = [{..},{..}...];
...
<ul>
  data.map(item => <li>{item.text}</li>);
</ul>

This is post rendering on client side, SEO won’t see the list of ul-lis. So, how is that this getStaticProps() making SEO happier? Or am I misunderstanding it? It doesn’t make SEO happier.

Is google crawler able to read the delayed set of meta description in client side rendering website?

Currently I have a client side rendering website where it will fetch the data from API and set it as content. For SEO I planned to implement this blog to make my client side web able to set meta description based on the content.
So my website will:

  1. Fetch data content from API
  2. Set meta description based on the content fetched using the technique described here.
  3. Render the content.

My question is, is google crawler able to read that delayed meta description and make the google search result for my wbesite be better?

I haven’t tried anything, my question is absolutely a theoritical issue.

ngx chips sorting after editing the chips doesn’t work in chrome but working in firefox

I am using ngx chips and I am trying to edit the tags after adding and called a sorting functin to sort them it’s working as expected in firefox but not in chrome. is there any browser issue ?

tags.component.html

  <tag-input [id]="field.fieldId" [formControlName]="field.fieldName" [(ngModel)]='field.defaultValue' class="form-control" [displayBy]="'text'" (onTagEdited)="onTextChangeInput($event)" (onAdd)="onItemAdded($event)" (onRemove)="onItemRemoved($event)" [placeholder]="field.otherProperties.placeholder"  [editable]="!field.otherProperties.disabled" [identifyBy]="'text'" [secondaryPlaceholder]="field.otherProperties.placeholder"  [disable]="field.otherProperties.disabled"></tag-input>

tags.component.ts

 onTextChangeInput(value:any) {
    this.isModified();
    debugger;
    if(this.field.defaultValue[value.index] && this.field.defaultValue[value.index].text){
      this.field.defaultValue[value.index].text = value.tag.text;
    }
    this.field.defaultValue = this.sortByText(this.field.defaultValue);
}

sorting function

  sortByText(data:any):any{
    let nameA:any;
    let nameB:any;
    let returnedValue:any =   data.sort((a:any, b:any) => {
      if(this.field.valueType !== 'string'){
        nameA = a.text.toUpperCase();
        nameB = b.text.toUpperCase();
      }
      else{
        nameA = a.toUpperCase();
        nameB = b.toUpperCase();
      }
      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }
      return 0;
    })
    return returnedValue;
  }

It’s work as expected in firefox browser but not in chrome

How to enable clicks on element under $(‘#parent’).click(false)? [duplicate]

I am having a popup window which I want to be able to close by clicking next to it, but obviously not on it. I therefore have code like this:

$('#popupWindow').click(false);
$('#overlayBackground').click(function(){
  $(this).css('display', 'none');
});
#overlayBackground{
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
}
#popupWindow{
  width: 25%;
  height: 25%;
  margin: auto;
  transform: translateY(50px);
  text-align: center;
  background-color: #FFF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="overlayBackground">
  <div id="popupWindow">MyPopup</div>
</div>

This make all clicks on the background close the popup but no clicks on the popup itself close it. However, now I have a checkbox on the popup window like below:

$('#popupWindow').click(false);
$('#overlayBackground').click(function(){
  $(this).css('display', 'none');
});
#overlayBackground{
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
}
#popupWindow{
  width: 25%;
  height: 25%;
  margin: auto;
  transform: translateY(50px);
  text-align: center;
  background-color: #FFF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="overlayBackground">
  <div id="popupWindow">
    <input type="checkbox">
  </div>
</div>

This checkbox won’t accept clicks due to the code $('#popupWindow').click(false);.

What I tried

I tried adding some jQuery to check the box but this code doesn’t change the checkbox value either, no matter if I put it first or last in the JS document:

$('#myCheckbox').click(function(){
    $(this).prop('checked', !$(this).prop('checked'));
});

Questions

  1. How do I make the checkbox clickable?
  2. Is there a better way to close the popup when clicking outside of it than what I have done which would allow me to click checkboxes inside the popup?

Convert Local time into Long format from openweather Api

I obtained data from open weather API

dt:1679888142
timezone:7200

I’m trying to change UNIX time into local time by applying Date object in JavaScript followed by toUTCString() to get the local time.

The goal is to change the obtained local time 'Mon, 27 Mar 2023 05:35:42 GMT' into long formatted time eg 'Monday, March 27 at 4:35 AM'. when i apply the following code, its not formatting also adding my timezone difference to it

this is the following code

  let epochtime = weatherData.dt;
  let timezone = weatherData.timezone;
  const rfc2822Date = new Date((epochtime + timezone) * 1000).toUTCString();

  const options = {
    weekday: "long",
    month: "long",
    day: "numeric",
    hour: "numeric",
    minute: "numeric",
    hour12: true
  };
const longFormatDateTime =  rfc2822Date.toLocaleString("en-us",options);

i tried to pass the date once again into date object which will result in gmt+timezone and format. formatting seems to work but local time is wrong

Async coding / Returning promise values in Vanilla Javascript

I am new to Javascript and trying to build in async code but having an issue and hoping someone may be able to point out where I am going wrong.

  1. I have a function that returns a promise successfully.
  2. I have an event listener that calls the function and passes 4 parameters to the function
  3. I then am trying to pass the results to a new function to print them to the front end.

The function in pt 1 works successfully but what is appearing to happen is that the event listener will not wait for the returned promise before proceeding and therefore it will not pass anything to the front.

Below is all the aspects of the code involved.

  1. The function that returns the promise successfully.

async function getFlightsData(
  param1 = "Any",
  param2 = "Any",
  param3 = "Any",
  param4 = "Any"
) {
  // create new data copy
  const clone = JSON.parse(JSON.stringify(flightsDataNew));
  // Map function
  const results = clone
    .map((flight) => {
      return findDistance(flight);
    })
    .map((flight) => {
      return setTime(flight);
    })
    .map((flight) => {
      return lookForFlightsGoingFrom(flight, param1);
    })
    .filter((el) => el !== undefined)
    .map((flight) => {
      return lookForFlightsGoingTo(flight, param2);
    })
    .filter((el) => el !== undefined)
    .map((flight) => {
      return findAirline(flight, param3);
    })
    .filter((el) => el !== undefined)
    .map((flight) => {
      return findAircraft(flight, param4);
    })
    .filter((el) => el !== undefined)
    .map((flight, index) => {
      flight.timestamp = [];
      const newTimeStamp = new Date().toISOString();
      flight.timestamp.push(newTimeStamp);
      flight.numberOfFlights = index;
      return flight;
    });
  return results;
}

  1. The event listener code

async function updateFlightsDataTextInput(event) {
  let value = event.target.value;

  let value1 = document.querySelector("#filterSourceAirportSelect").value;
  let value2 = document.querySelector("#filterDestinationAirportSelect").value;
  let value3 = document.querySelector("#filterAirlineSelect").value;
  let value4 = document.querySelector("#filterAircraftSelect").value;

  if (
    value1 === "Select" &&
    value2 === "Select" &&
    value3 === "Select" &&
    value4 === "Select"
  ) {
    document.querySelector("#flightFilterDisplayDiv").innerHTML = "";
  } else {
   
// ** THIS CALLS FUNCTION 1 SEE ASYNC BELOW but wont return the promise.
    (async function () {
       let newP = new Promise((resolve) => {
         const results = flightDataAnswer(value1, value2, value3, value4);
         if (results !== undefined) {
           resolve(results);
           console.log(XXXXXXX);
           console.log(results);
         } else {
           console.log(results);
           console.log("error");
         }
         console.log(results);
       });
     })();
//** THIS PASSES TO THE RESULTS THE FRONT END
     newP.then(() => {
       flightsDataCopyForDOM(results);
     });
  }
}

Property ‘find’ does not exist on type ‘object’.ts(2339)

I am running into this type error with the .find method. I know this is a tsconfig.json lib issue but I read every single article and none of the solutions worked for me.

I tried adding to the lib list: es5, es2015, es6, es2016, es7, es2017, es2018, es2019, etc. one by one.
I also tried adding all those to the target as well

My typescript version is 4.9.4

This is my tsconfig.json:

  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": false,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl": ".",
  {...}

Thanks!

Fetch and asyncData not running in Nuxt3 page

In Nuxt3 I’m trying to utilize asyncData (in a much longer script). It wasn’t running at all (no errors in console, just didn’t execute) so I attempted simple tasks with asyncData and then fetch, neither of which ran either. Setup runs just fine so it’s not as if nothing on the page is executing. I’m new to Nuxt3 so unsure if I’m making a simple mistake. (Running in a page, not a component)

import { useMainStore } from '~~/store'

export default {
  name: 'LandingPage',
  components: {
    FinalLandingPage
  },
  async fetch(){
    console.log("fetch running")
  },
  setup() {
    const store = useMainStore();
    // console.log(store.discord)
    return { store }
  },
  // mixins: [previousDataMixin],
  async asyncData({ app }) {
        console.log("running")
}

Trying to complete a kata on codewars and my code passes all the given tests except the random test where it messes up my result?

https://www.codewars.com/kata/6375587af84854823ccd0e90/train/javascript
this is the kata..

this is my solution.. sorry for the format and the size but it works, or should, and i dont know why?

`function blockPrint(input){
  if (input.trim()=="") return"";
const string=input.trim().toUpperCase();    //trims off spaces and converts to uppercase
const map=[];
let output="";            // Uses the exact requirements given in expected output as shown below 
let pos=0;
map[0]=" AAA  BBBB   CCC  DDDD  EEEEE FFFFF  GGG  H   H IIIII JJJJJ K   K L     M   M N   N  OOO  PPPP   QQQ  RRRR   SSS  TTTTT U   U V   V W   W X   X Y   Y ZZZZZ";
map[1]="A   A B   B C   C D   D E     F     G   G H   H   I       J K  K  L     MM MM NN  N O   O P   P Q   Q R   R S   S   T   U   U V   V W   W X   X Y   Y     Z";
map[2]="A   A B   B C     D   D E     F     G     H   H   I       J K K   L     M M M N   N O   O P   P Q   Q R   R S       T   U   U V   V W   W  X X   Y Y     Z ";  
map[3]="AAAAA BBBB  C     D   D EEEEE FFFFF G GGG HHHHH   I       J KK    L     M   M N N N O   O PPPP  Q   Q RRRR   SSS    T   U   U V   V W W W   X     Y     Z  ";
map[4]="A   A B   B C     D   D E     F     G   G H   H   I       J K K   L     M   M N   N O   O P     Q Q Q R R       S   T   U   U V   V W W W  X X    Y    Z   ";  
map[5]="A   A B   B C   C D   D E     F     G   G H   H   I       J K  K  L     M   M N  NN O   O P     Q  QQ R  R  S   S   T   U   U  V V  W W W X   X   Y   Z    ";  
map[6]="A   A BBBB   CCC  DDDD  EEEEE F      GGG  H   H IIIII JJJJ  K   K LLLLL M   M N   N  OOO  P      QQQQ R   R  SSS    T    UUU    V    W W  X   X   Y   ZZZZZ";

 


  
  for (let i=0;i<7;i++){
  for(let j=0;j<string.length-1;j++){
    pos=(string.charCodeAt(j)-65)*6;    // works out which bit to add     
    if (pos=>0 && pos<=91){                        // and if its not a space
     output+=(map[i].slice(pos,pos+6)); // adds it
      }                                      //just do up till the last char because of test requirement for no trailing spaces
    
    if((pos/6)+65<65) {                // or if it is a space
        output+="      ";                // adds a space of 6 "spaces"
      }
            
  }
    pos=(string.charCodeAt((string.length)-1)-65)*6;        // finds the last char
    output+=(map[i].slice(pos,pos+6)).trimEnd();        // adds the bit with its "end" trimmed off as per the test requirements
    
 if(i<6) {output+="n";}   //this to ensure no added carriage returns are added at the end as per test requirements 
  
} 
  
  
 console.log(output); 
  return output;
  
}`

I tried the above code, which passes all the given tests but for some weird reason, when its given “30 random chars” (which is anything up to 30) it either looks like it should pass (console log shows a match to expected output) or somehow it messes up the result by removing white spaces from the result or adding loads of random characters?? it seems to build up errors the more times I “attempt” it, I asked what was goin on and someone marked my question as “containing spoiler”??
Im guessing then, for that reason. I’m missing something fundamental about how javascript handles the data, or the way codewars tests work?