Home > database >  How to convert file contents into strings?
How to convert file contents into strings?

Time:11-13

I have a txt file that looks like this:

1||fun||ball
2||job||hammer
3||run||feet

I want to load that into my code and convert it to:

<dt>1</dt><dd>fun <img src="ball.png"></dd>
<dt>2</dt><dd>job <img src="hamm.png"></dd>
<dt>3</dt><dd>run <img src="feet.png"></dd>

I tried like this:

const openrooms = `1||fun||ball
     2||job||hamm
     3||run||feet`;

const roomlist = openrooms.split('\n');

for (var rooms in roomlist) {
  room = roomlist[rooms].split('||');
  for (var {roomid, name, icon} in room) {
    result = `<dt>${room[roomid]}</dt><dd>${room[name]} <img src="${room[icon]}"></dd>`;
  }
}
document.getElementById("destination").innerHTML = result;
<div id="destination"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

all I get is undefined. Why is that? Please try the fiddle below:

https://jsfiddle.net/db6hy8a0/

CodePudding user response:

Try:

const openrooms = `1||fun||ball
     2||job||hamm
     3||run||feet`;

const roomlist = openrooms.split('\n');

const result = roomlist.map(e => {
  var split = e.split('||')
  return `<dt>${split[0]}</dt><dd>${split[1]} <img src="${split[2]}.png"></dd>`
}).join('')

document.getElementById("destination").innerHTML = result;
<div id="destination"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The second loop attempts to destructure the strings from the second split.

Try something closer to:

const openRooms = `1||fun||ball
2||job||hammer
3||run||feet`
 
const rooms = openRooms.split('\n')

result = ""
rooms.forEach(room => {
  const [id, name, icon] = room.split('||')
  result  = `${id} room: ${name} - ${icon}\n`
})

console.log(result)
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

(Although why not just store them in an object in the first place?)

CodePudding user response:

const openrooms = `1||fun||ball
 2||job||hamm
 3||run||feet`;


const result = openrooms.split("\n").map((row)=>{
const items = row.split("||");
return `<dt>${items[0]}</dt><dd>${items[1]} <img src="${items[2]}.png"></dd>`})


document.getElementById("destination").innerHTML = result;
  • Related