javascript printing array into paragraphs - javascript

I am trying to make a local html to display some text from txt file (also local).
I used this to read file into array and print it:
<input type="file" name="files" id="inputfile">
<script type="text/javascript">
document.getElementById('inputfile')
.addEventListener('change', function() {
var test=new FileReader();
test.onload=function(){
document.getElementById('output')
.textContent=fl.result;
}
test.readAsText(this.files[0]);
})
</script>
However, I would like to print it from the array into paragraphs, line by line (first line goes into heading, second into paragraph, third into heading and so on...).
Is there a way to do it automaticaly from an array, or would I have to do it by hand for each one?
I am kinda green in javascript so I would rather refrain from using node etc.

If the headers and paragraphs are always strictly alternating, you can check whether each array index is odd or even to decide whether to wrap it in header or paragraph tags. One way:
arr = ["header", "paragraph", "header", "paragraph", "header", "paragraph"]
joined = arr.map((el, i) => {
return (i % 2 === 0) ? `<h1>${el}</h1>` : `<p>${el}</p>` ;
}).join('')
console.log(joined)

const arr = ['Heading 1','Para1','Heading 2','Para2','Heading 3','Para3'];
const result = arr.map((val, i) => i%2===0 ? `<h2>${val}</h2>` : `<p>${val}</p>`).join('');
document.getElementById('output').innerHTML = result ;
<div id="output"></div>

Put this in your code:
function arrToPar(arr){ //For JS-Array --> HTML content
var out = "";
for(var i = 0; i < arr.length; i++){
out += arr[i] + "<br>";
}
return(out);
}
Or...
function arrToString(arr,joiner = " "){ //For JS-Array --> JS-String
var out = ""; //The parameter "joiner", by default, is a space
//This means that you only need to specify "arr", but you can do
//a second parameter. This function behaves like arr.join(joiner).
for(var i = 0; i < arr.length; i++){
out += arr[i] + joiner;
}
}

Related

Displaying images with given URL in a json string on a html page

I am working on a project where I call a certain API and in response I get back a json string with all the information. I need to find a way using javascript to display this json string into a table format. I got a very basic version of this running. However, the problem I am having is that I cannot find a way to display a image in this block of code.
results.html file:
<!DOCTYPE HTML>
<html>
<head>
<title>
How to convert JSON data to a
html table using JavaScript ?
</title>
<h1>Results: </h1>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body style = "text-align:center;" id = "body">
<h3>Showing resuls for: {{searchQuery}}</h3>
<p>{{responseText}}</p>
<br><br>
<table align = "center"
id="table" border="1">
</table>
<div id="header"></div>
<script>
var el_up = document.getElementById("GFG_UP");
var list = [];
list = "{{responseText|escapejs}}";
//console.log(list);
var titles = []
for (var i = 0; i < list.length-8; i++) {
if(list[i] == 't' && list[i+1] == 'i')
{
var title = '';
for(var j = (i+8); list[j] != ","; j++) {
title += list[j];
}
i = j;
console.log(title + ", ")
titles.push(title)
}
}
console.log(titles)
var images = []
for (var i = 0; i < list.length-8; i++) {
if(list[i] == 'h' && list[i+1] == 't')
{
var image = '';
for(var j = (i); list[j] != ","; j++) {
image += list[j];
}
i = j;
console.log(image + ", ");
var img = new Image();
img.src = image.slice(0, -1);
images.push(img);
}
}
console.log(images)
var restaurants = []
for (var i = 0; i < list.length-17; i++) {
if(list[i] == 'r' && list[i+1] == 'e' && list[i+2] == 's')
{
var restaurant = '';
for(var j = (i+17); list[j] != ","; j++) {
restaurant += list[j];
}
i = j;
console.log(restaurant + ", ")
restaurants.push(restaurant)
}
}
console.log(restaurants)
function createTable(tableData) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
console.log(typeof(cellData))
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
})
table.appendChild(tableBody);
document.body.appendChild(table);
};
var a = [titles, restaurants, images]
console.log(a)
createTable(a);
</script>
</body>
</html>
The function createTable is the one in question. It displays the text parts correctly. Im not sure how to get it to display images given the URLs of those images in a table.
output HTML file:
HTML output
You should show us the API response you are working with here.
Another thing is your createTable function expects to get table data. But onclick on your button pass there #table ID. Not sure if it should be like this.
Also you could run your JS script when all page is loaded:
window.onload = () => {
// Your JS script which should do something after page is loaded.
}
Finally it comes to the images. I think that you are not using img tag anywhere so your images simply won't be visible in the table. If you would like to see them just create img element and put it into td.
Few advices (not related with your question):
stop using console.log so much, place debugger statement in your code and debug it like a pro, if you don't know how just look for it in youtube,
please put your attention to a code style, it is a bit messy, if you have real trouble with it use ESlint to fix it for you.
EDIT
About images - if you want to create DOM element for img use code below instead of current one:
var img = document.createElement("IMG");
Than you can set src and other things like alt and so on:
img.src = imgUrlString;

Returning customize Array value

I have a sample of code that returns each value in an array, in order. I have used forEach(). Is there any way to return value in customize array.
I made some function for split text-area value to all textarea and query using text string. I am able to success. But Some Problem. Below Example.
Type to Filed1 string like:
GFSD65897542
Then Click Split Button. Output: part all value to reaming text area.
Put GF value to Input Character Filed. Output: 6589
My Question is When i put value like GF then output 6589. And when put FG then also same output 6589 instead of 8965. If any solution Pls help me out. I wish to the Character strictly follow number.
Sample of Code:
$('#output1').focus(()=>{
var a=document.querySelectorAll('textarea');
var str = $('#ccMain').val();
var first = str[0];
var second = str[1];
console.log(first," ", second)
var str='';
a.forEach(e=>e.value.includes(first)||e.value.includes(second)?str+=e.value.substr(1,e.value.length):false)
$('#output1').val(str);
})
function splitText() {
var textAreas = [];
//Put all of the textareas into an array for easy access
for(let i = 1; i <= 4; i++) {
textAreas.push(document.getElementById(`value${i}`));
}
//Read the text from text1 and split it at a new line
var text = textAreas[0].value;
var [line1, line2] = text.split(/\r?\n/)
for(let i = 0; i < 4; i++) {
var combinedText = line1.substring(i, i+1) + line2.substring(i*2, (i+1)*2)
textAreas[i].value = combinedText;
}
}
$('#output').focus(()=>{
var a=document.querySelectorAll('textarea');
var str = $('#ccMain').val();
var first = str[0];
var second = str[1];
console.log(first," ", second)
var str='';
a.forEach(e=>e.value.includes(first)||e.value.includes(second)?str+=e.value.substr(1,e.value.length):false)
$('#output').val(str);
})
<html>
<head>
<title>Test Demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<label>Filed1 </label>
<textarea id="value1"></textarea>
<label>Filed2:</label>
<textarea id="value2"></textarea>
<label>Filed3:</label>
<textarea id="value3"></textarea>
<label>Filed4:</label>
<textarea id="value4"></textarea>
<button onclick="splitText()">Split!</button>
<br>
<label>Input Character:</label>
<br>
<input type="text" id="ccMain" >
<textarea id="output"></textarea>
</body>
</html>
I would use a map to put the correspondence between letter and digits
$('#output').focus(()=>{
var textareas = document.querySelectorAll('textarea');
var map = new Map(Array.from(textareas, area => [area.value[0], area.value.slice(1)]));
var str = Array.from($('#ccMain').val(), c => map.get(c)).join``;
$('#output').val(str);
});
function splitText() {
//Put all of the textareas into an array for easy access
var textAreas = [];
for(let i = 1; i <= 4; i++) {
textAreas.push(document.getElementById(`value${i}`));
}
//Read the text from text1 and split it at a new line
var text = textAreas[0].value;
var [line1, line2] = text.split(/\r?\n/);
for (let i = 0; i < 4; i++) {
var combinedText = line1.substring(i, i+1) + line2.substring(i*2, (i+1)*2)
textAreas[i].value = combinedText;
}
}
$('#output').focus(()=>{
var textareas = document.querySelectorAll('textarea');
var map = new Map(Array.from(textareas, area => [area.value[0], area.value.slice(1)]));
var str = Array.from($('#ccMain').val(), c => map.get(c)).join``;
$('#output').val(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Filed1 </label>
<textarea id="value1"></textarea>
<label>Filed2:</label>
<textarea id="value2"></textarea>
<label>Filed3:</label>
<textarea id="value3"></textarea>
<label>Filed4:</label>
<textarea id="value4"></textarea>
<button onclick="splitText()">Split!</button>
<br>
<label>Input Character:</label>
<br>
<input type="text" id="ccMain" >
<textarea id="output"></textarea>
Well you have to be a bit more careful in your code here, ou are defining str twice in your code block.
As far as what you want to achieve, I guess you want to go for something like
str = Array.from( a )
.filter( e => e.value.includes( first ) || e.value.includes( second ) )
.map( e => e.value.substring( 1 ) )
.join('')
this would first create an array from your nodes, using Array.from and then you can filter the values you are really interested in, after which you can take the substring of the values (you don't need the e.value.length, as this is the same as when you are just defining a startIndex in the substring method

How to manipulate the characters written in a div to work with them afterwards using javascript

function doGetWord(){
var word = F.gword.value;
var wLength = word.length;
for(var i = 0; i < wLength; i++){
document.getElementById("dword").innerHTML += "_ "
}
}
This is a function that will write _ in a div in html, and what I want is to change them if the user types the corresponding input, for example if the first letter is supposed to be "a" then it would change the first _ to "a".
This is what I got so far:
function doGuessWord(){
dummy = F.t.value
if(dummy.length > 1){
dummy = ""
F.t.value = ""
}
for(var x = 0; x < wLength; x++){
if (substr(x, wLength) == dummy ) {
document.getElementById("dword").innerHTML += "_ "
}
else{
document.getElementById("dword").innerHTML += "dummy "
}
}
}
Could you help me out with this one?
Thanks in Advance!!
Something like this?
https://jsfiddle.net/9z66968a/3/
You will have to adapt it a bit. But you should be able to take the parseText function and pass it the params you need to return the text to insert where ever you want
There you go. I believe this is what you wanted. Feel free if you don't understand something
https://jsfiddle.net/vhsf8gpp/2/
var dashArr = [];
var dummyWord = document.getElementById('dummy');
var input = document.querySelector('input');
var counter = 0;
for(let i= 0; i<10;i++)
{
dashArr.push('_');
}
function WriteContent()
{
dummyWord.textContent = dashArr.map(d=>d).join(''); // This gets rid of the ',' inbetween the dashes
}
WriteContent();
//var charArr = [];
document.querySelector('input').addEventListener('keyup',function(){
var inputString = input.value;
dashArr[counter] = inputString.charAt(inputString.length - 1);
WriteContent();
counter++;
})
I used this post for reference.

Making list from textarea value by new lines

This may be very easy to solve but my brain is dead for some reason I can't find out the right road to success :(
I have some text area where by pressing enter for each word or more words in one line I get an list item.
$(document).on('click','#addList', function(){
var lines = $('#list').val().split(/\n/);
var texts = []
for (var i=0; i < lines.length; i++) {
if (/\S/.test(lines[i])) {
texts.push($.trim(lines[i]));
}
}
var list = JSON.stringify(texts);
for(var e=0; e<list.length; e++){
var li = li+'<li class="c1_2v">'+list[e]+'</li>';
}
$('.content').append($('<ul>'+li+'</ul>'));
});
By doing this $.trim I am getting problem if I have more words in one line but it is useful if I have more empty new lines or spaces before first word.
Example:
<textarea>
this is
a
something
that
I want to add to new lists
</textarea>
By my code and first for loop I get something like: ['this','is','a','something','that','I','want','to','add','to','new','lists']
By second for loop I get into li tags every letter or character from [ to ] inside li tags
I don't understand regex I saw many websites but it is not getting into my head so even if you add it as more easier answer without explanation what is used for what I wouldn't know how it works..
And this is basically what I need to get in .content div:
<ul>
<li class="c1_2v">this is</li>
<li class="c1_2v">a</li>
<li class="c1_2v">something</li>
<li class="c1_2v">that</li>
<li class="c1_2v">I want to add to new lists</li>
</ul>
I will add snippet how it works till now:
$(document).on('click','#addList', function(){
var lines = $('#list').val().split(/\n/);
var texts = []
for (var i=0; i < lines.length; i++) {
if (/\S/.test(lines[i])) {
texts.push($.trim(lines[i]));
}
}
var list = JSON.stringify(texts);
for(var e=0; e<list.length; e++){
var li = li+'<li class="c1_2v">'+list[e]+'</li>';
}
$('.content').append($('<ul>'+li+'</ul>'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="list"></textarea>
<button id="addList">Add</button>
<div class="content"></div>
And also there is something undefined Idk what :(
As #AlexKudryashev commented I used array as string not as array and if I add var li before for loop undefined will go away.
$(document).on('click', '#addList', function() {
var lines = $('#list').val().split(/\n/);
var texts = []
for (var i = 0; i < lines.length; i++) {
if (/\S/.test(lines[i])) {
texts.push($.trim(lines[i]));
}
}
//var list = JSON.stringify(texts);
var list = texts;
var li = "";
for (var e = 0; e < list.length; e++) {
li = li + '<li class="c1_2v">' + list[e] + '</li>';
}
$('.content').append($('<ul>' + li + '</ul>'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="list"></textarea>
<button id="addList">Add</button>
<div class="content"></div>
JSON.stringify converts the value to JSON string. So you are looping every string instead of the array. Also, you were getting undefined since li is not defined. To avoid simply define li as "" empty string.
Here is a simplified solution that requires no regex. You can use array.filter and array.map to consolidate.
document.querySelector('button').onclick = () => {
var text = document.querySelector('textarea').value;
var lines = text.split('\n');
var html = lines
.filter(line => line.trim() !== '')
.map(line => `<li class="c1_2v">${line}</li>`)
.join('');
document.querySelector('ul').innerHTML = html;
}
<textarea>
this is
a
something
that
I want to add to new lists
</textarea>
<button>Click me</button>
<ul><!--output goes here--></ul>

removing a pipe sign from text with javascript

I have some text that I am rendering using underscore and it contains pipe character that I am trying to remove.
This is what I have tried
<script type="text/html" id="activityDescriptionTmpl">
<%= formatInput(container.CurrentActivity.ProcessActivityDescription) %>
</script>
this is what the text looks like
This is the text with pipe character at the end|
This id a javascript function I created
formatInput = function (input) {
var arr = [];
var finalInput = '';
if (input.indexOf('|') > 0) {
arr = input.split('|');
for (var i = 0; i < arr.length; i++) {
if ($.trim(arr[i]).length > 0)
finalInput += $.trim(arr[i]) + '<br />';
}
}
else {
finalInput = input;
}
return finalInput;
};
But in this case I get the errorcannot read property 'indexOf' undefined
Is there perhaps a better way of just removing this pipe character
Try newInput = input.replace("|", "");
http://jsfiddle.net/robschmuecker/sGKf3/

Categories