Create an HTML table using Javascript Array - javascript

parse the given array (using JavaScript) and create an HTML table
Gmail - containing all email ids with domain gmail.com.
Yahoo - containing all email ids with domain yahoo.com.
Others - containing all email ids with domains not in a,b, and c, i.e., NOT gmail, hotmail and yahoo.
I want to segregate the array of emailids based on domain and show them in html table. I have tried the following code , but it doesnt work at if condition. Please help me solve this problem or alternate solution
----------
<script>
// var email ="test#gmail.com"
// var domain = email.replace(/.*#/," ");
// alert(domain);
var d1 = "gmail.com"
var d2 = "hotmail.com"
var d3 = "yahoo.com"
var email =[" test#gmail.com", "test#hotmail.com" , "test#yahoo.com"];
var i;
// var domain = email.replace(/.*#/," ");
var text = "";
for(i=0;i<email.length;i++){
var dom = email[i].replace(/.*#/," ");
if(dom[i]==d1){
// text += email[i] + "<br>";
// document.getElementById("demo").innerHTML = text;
document.write("hii hello");
}
// else if(dom == "hotmail.com"){
// // text += email[i] + "<br>";
// // document.getElementById("demo").innerHTML = text;
// document.write("hii");
// }
// else if(dom == "yahoo.com"){
// // text += email[i] + "<br>";
// // document.getElementById("demo").innerHTML = text;
// document.write("swax");
// }
else{
document.write(dom); }
}
// document.getElementById("demo").innerHTML = text;
</script>

.replace(/.*#/," ");
You should replace with an empty string
.replace(/.*#/,"");
By the way, it's not really recommended to use document.write().
To help you I wrote quickly this snippet as starting point for you (no judgement, I barely tested it):
function createTable(rows) {
const table = document.createElement('table');
for (row of rows) {
const tr = document.createElement('tr');
for (column of row) {
const td = document.createElement('td');
td.appendChild(document.createTextNode(column));
tr.appendChild(td);
}
table.appendChild(tr);
}
document.body.appendChild(table);
}
const emails = [
'test0#gmail.com', 'test0#hotmail.com', 'test0#test.com',
'test1#gmail.com', 'test1#hotmail.com', 'test1#test.com',
];
const split = [[], [], []];
emails.forEach(email => {
switch (email.split('#')[1]) {
case 'gmail.com': split[0].push(email); break;
case 'hotmail.com': split[1].push(email); break;
default: split[2].push(email)
}
});
createTable(split);
Regards,
Vincent

Related

How to loop properly

So here is the overall of what I need to do
Start with confirming if the user wants to add a course, if they click ok it gives them a prompt to enter course if they hit cancel it finishes the program.
When the user gives an answer to the course, they then need to give their grade for that specific course.
Once those two questions are done it needs to go back to ask them if they want to add a course again
this is what i have so far
while (true) {
var entering = confirm('Do you want to enter a Course?');
if (entering = true) {
break;
}
}
var codeInput = '';
var gradeInput = '';
while (true) {
codeInput = prompt('Enter Course Code');
if (codeInput.length === 7) {
break;
}
alert('invalid code');
}
gradeInput = prompt('Enter Grade for ' + codeInput + '');
document.writeln('<table border="1">');
document.writeln('<tr>');
document.writeln('<th>Course Code</th>');
document.writeln('<th>Grade</th>');
document.writeln('<tr>');
document.writeln('<th>' +
codeInput +
'</th>');
document.writeln('<th>' +
gradeInput +
'</th>');
document.writeln('</tr>');
So I'm not sure how to loop it back to the start and how to make the program stop when you hit cancel when it asks if you want to add another course. I also do not know how to make it so if the user asks to enter another course/grade how to make them into a separate answer to add below in the table.
I hope this makes sense and if anyone can help would be lovely thank you!
ps. This has to all be done using javascript no HTML.
Working fiddle.
Wrap your code in a function so you could call it every time you enter the grad to ask it again.
I suggest to create the table and the header then append the rows when the user answers the prompts :
var number_of_rows = 0;
var table = document.createElement('table');
table.border = '1';
ask();
function ask() {
var codeInput = '';
var gradeInput = '';
var entering = confirm('Do you want to enter a Course?');
if (!entering) {
return;
} else {
while (true) {
codeInput = prompt('Enter Course Code');
if (codeInput.length === 7) {
break;
}
alert('invalid code');
}
}
gradeInput = prompt('Enter Grade for ' + codeInput + '');
if (number_of_rows === 0) {
var row = document.createElement('tr');
var th_1 = document.createElement('th');
var th_2 = document.createElement('th');
var txt_1 = document.createTextNode("Course Code");
var txt_2 = document.createTextNode("Grade");
th_1.appendChild(txt_1);
th_2.appendChild(txt_2);
row.appendChild(th_1);
row.appendChild(th_2);
table.appendChild(row);
number_of_rows++;
}
console.log(number_of_rows);
table = insertRow(codeInput, gradeInput);
document.body.appendChild(table);
number_of_rows++;
ask();
}
function insertRow(codeInput, gradeInput) {
var row = document.createElement('tr');
var td_1 = document.createElement('td');
var td_2 = document.createElement('td');
var txt_1 = document.createTextNode(codeInput);
var txt_2 = document.createTextNode(gradeInput);
td_1.appendChild(txt_1);
td_2.appendChild(txt_2);
row.appendChild(td_1);
row.appendChild(td_2);
table.appendChild(row);
return table;
}
According to here https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt
If the user clicks the Cancel button, this function returns null
So all you need is to check if value is null to know if the user clicked cancel
if (codeInput == null) break

How to dynamically add <a> tags given an index of HTML page's string?

I'm making a search function for my website. So far, I've found the string the user searches for in the whole website, and I'm able to print the string and the context of the string. I have achieved this by using $.get on my HTML pages, then stripping the HTML to leave the pure text I want to search in. I then find the index of the string I'm looking for, then use substr to find the context of the input string (a few indexes ahead and behind).
Now, I need to link to the original page when a user clicks on a search result. My research says to use <a> tags, but how do I dynamically insert those into the HTML page with the index I have? And the index I have isn't even the complete page; it's stripped of tags.
These are the relevant parts of my code:
JavaScript:
function getIndicesOf(searchStr, str) { //get the indices of searchStr inside of str
var searchStrLen = searchStr.length;
if (searchStrLen == 0) {
return [];
}
var startIndex = 0, index, indices = [];
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
return indices;
}
function search() {
obj=document.getElementById("searchButton");
obj.onclick = function() {
var searchInput = document.getElementById('searchBox').value;
var allPageContent = ['chap/telem.php', 'chap/nestor.php', 'chap/aeolus.php', 'chap/calypso.php', 'chap/circe.php', 'chap/cyclops.php', 'chap/eumaeus.php', 'chap/hades.php','chap/ithaca.php', 'chap/lestry.php', 'chap/lotus.php', 'chap/nausicaa.php', 'chap/oxen.php', 'chap/penelope.php', 'chap/proteus.php', 'chap/scylla.php', 'chap/sirens.php', 'chap/wrocks.php']; //contains all text
var allText = '';
for (var i = 0; i < allPageContent.length; i++){
$.get(allPageContent[i], function(data){
var div = document.createElement("div");
div.innerHTML = data;
//allText = div.textContent || div.innerText || ""; //gets the text to search in, stripped of html
alltext = data;
allText = allText.replace(/(\r\n\t|\n|\r\t)/gm," ");
console.log(data);
var indices = getIndicesOf(searchInput, allText); //the variable indices is the array that contains the indices of the searched text in the main text
indices.forEach(findContext);
})
}
localStorage.output = '';
function findContext(currentValue, index) {
if (currentValue <= 16) {
searchContext = "..." + allText.substr(currentValue, 100) + "...";
} else {
searchContext = "..." + allText.substr(currentValue-15, 100) + "...";
}
localStorage.output = localStorage.output + searchContext + "<br /><br />";
}
console.log(localStorage.output);
};
};
HTML:
<script>document.getElementById("output").innerHTML = localStorage.output;</script>
It's a bit confusing what you're trying to achieve, considering your HTML, but replying to this
My research says to use <a> tags, but how do I dynamically insert
those into the HTML page with the index I have?
this would do the trick
var output = document.getElementById("output");
var a = document.createElement("a");
var linkText = document.createTextNode("my linked text");
a.appendChild(linkText);
a.href = "http://example.com";
output.appendChild(a);

Speeding up UrlFetch Google App Scripts?

The goal is to run through about 10,000 lines of links. Determine which have page numbers > 3 and highlight the first column. I have all of this done, but the problem is that it takes Url Fetch too long, I run into a maximum run time error. Is there anyway I can speed up this code so I can run through the 10,000 lines?
function readColumns() {
//program is going to run through column 3 by going through the amount of rows, truncating last three characters to see if pdf, then highlighting first column
var sheet = SpreadsheetApp.getActiveSheet();
var columns = sheet.getDataRange();
var rowNum = columns.getNumRows();
var values = columns.getValues();
var html;
var htmlString;
for(var i = 1; i <= rowNum; i++){
var columnLogger = values[i][2];
try{
html = UrlFetchApp.fetch(values[i][2],
{
muteHttpExceptions: true,
}
);
}catch(e){
Logger.log("Error at line " + i);
var error = true;
}
htmlString = html.getContentText();
var index = htmlString.indexOf("Pages") + 6;
var pageNumber = parseInt(htmlString.charAt(index),10);
var lastChars = "" + columnLogger.charAt(columnLogger.length-3) + columnLogger.charAt(columnLogger.length-2) + columnLogger.charAt(columnLogger.length-1);
if((error) || (!lastChars.equals("pdf") && values[i][6].equals("") && !pageNumber >= 3)){
//goes back to first column and highlights yellow
var cellRange = sheet.getRange(1, 1, rowNum, 3)
var cell = cellRange.getCell(i+1, 1)
cell.setBackground("yellow");
}
}
}
Edit - short scripts:
function foreverCall(){
var start = 1480;
for(;;){
readColumns(start);
start = start + 100;
}
}
function readColumns(start) {
//program is going to run through column 3 by going through the amount of rows, truncating last three characters to see if pdf, then highlighting first column
var sheet = SpreadsheetApp.getActiveSheet();
var columns = sheet.getDataRange();
var rowNum = columns.getNumRows();
var values = columns.getValues();
var html;
var htmlString;
var error;
for(var i = start; i < start+100; i++){
if(loop(values, error, html, htmlString, rowNum, sheet, columns, i)){
var cellRange = sheet.getRange(1, 1, rowNum, 3)
var cell = cellRange.getCell(i, 1)
cell.setBackground("yellow");
}
}
}
function loop(values, error, html, htmlString, rowNum, sheet, columns, i){
var columnLogger = values[i][2];
var lastChars = columnLogger.slice(-4);
if(!lastChars.equals(".pdf") && values[i][6].equals("")){
return true;
}else{
try{
error = false
html = UrlFetchApp.fetch(values[i][2].toString());
if(html == null){
error = true;
}
}catch(e){
Logger.log("Error at line " + i);
error = true;
}
if(!error){
htmlString = html.getContentText();
var index = htmlString.indexOf("Pages") + 6;
var pageNumber = parseInt(htmlString.charAt(index),10);
}
//goes back to first column and highlights yellow
if(error || !pageNumber >= 3){
return true;
}
}
return false;
}
You can replace this:
var lastChars = "" + columnLogger.charAt(columnLogger.length-3) + columnLogger.charAt(columnLogger.length-2) + columnLogger.charAt(columnLogger.length-1);
With this:
var lastChars = columnLogger.slice(-3);
You could also initiate the fetch script from an html sidebar or dialog to run short batches and then return back to the success handler which could then initiate another batch depending upon the return value. The return value could also be used to start the next batch at the next row. It would actually take longer to run but you could probably stay well under the script limit by keeping your batches small.
You can replace with the line with
var lastChars = columnLogger.slice(-3);

Grab cell values from a table using Jquery?

I'm trying to grab the cell values from an HTML table generated from another PHP code. That I can use the result to send a rendezvous at final user.
My current JSFiddle can grab some values but not like I want. I need to retrieve the attrib title & value from the button in the TD, my problem is currently the code return data from morning day and jump to the next morning day.
How I can return entire day value & title data's for each available days in the table ?
Code :
$(document).ready(function(){
eachCell();
function eachCell(){
var cellInnerText = [];
var cellValue = [];
var out = document.getElementById("out");
var out2 = document.getElementById("out2");
$('#ft_agenda tbody tr').each(function(index) {
// console.log("index ", index, " this: " , this, "this.attr(rel)", $(this).attr('rel'), "$(this).text()", $(this).text());
console.log($(":first-child", $(this))[0]);
cellInnerText.push($("td button", $(this)).attr('value'));
cellValue.push($("td button", $(this)).attr('title'));
});
out.innerHTML = cellInnerText.join(" | ");
out2.innerHTML = cellValue.join(" | ");
}
});
// Try this code on your jsfiddle
// https://jsfiddle.net/g60ogt8c/1/
$(function() {
function findColumnByDate(date) {
var col;
$('#ft_agenda thead th').each(function(idx) {
if ($(this).text().trim() == date.trim()) col = idx;
});
return col;
}
function showAvailableTimes(date) {
var times = [],
column = findColumnByDate(date);
if (column) {
var $rows = $('#ft_agenda tbody td:nth-of-type('+column+')');
if ($rows.length) {
times[0] = '';
$rows.find('button').each(function() {
times[times.length] = $(this).attr('value')+' - '+$(this).attr('title');
});
times[0] = 'For date '+date+' found '+(times.length-1)+' free terms';
} else {
times[0] = ['No free terms for date: '+date];
}
} else {
times[0] = ['Invalid date '+date+' or date not found'];
}
return times;
}
// Function showAvailableTimes() now returns array.
// In index 0 is status message and if available times found,
// these lies on indexes 1 and more.
// Use it this way:
$('#out').html('');
showAvailableTimes('15-09-2016').forEach(function(item) {
$('#out').append(item + '<br>');
});
// Or this way:
// Jsonify returned array and send it toSome.php.
var json = JSON.stringify(showAvailableTimes('09-09-2016'));
$.post('toSome.php', {times: json});
// Or if there are free terms, filter status message
// and send just free terms - without status message.
var times = showAvailableTimes('09-09-2016');
if (times.length > 1) {
var json = JSON.stringify(times.filter(function(itm,idx){return idx>0}));
$.post('toSome.php', {times: json});
// Here you can see that status message was skipped
$('#out2').text(json);
}
});

Remove html formatting when getting Body of a gmail message in javascript

I would like to remove the html formatting in my google apps script. I am currently searching the email and printing the results to a google spreadsheet. I would like to know if there is a way to replace text.I am aware of regex but I dont think it works with the getBody function.
I would really appreciate some feedback or some help on this matter.
Code:
function Search() {
var sheet = SpreadsheetApp.getActiveSheet();
var row = 2;
// Clear existing search results
sheet.getRange(2, 1, sheet.getMaxRows() - 1, 4).clearContent();
// Which Gmail Label should be searched?
var label = sheet.getRange("F3").getValue();
// Get the Regular Expression Search Pattern
var pattern = sheet.getRange("F4").getValue();
// Retrieve all threads of the specified label
var threads = GmailApp.search("in:" + label);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var m = 0; m < messages.length; m++) {
var msg = messages[m].getBody();
// Does the message content match the search pattern?
if (msg.search(pattern) !== -1) {
// Print the message subject
sheet.getRange(row,3).setValue(messages[m].getBody());
Replace this:
// Print the message subject
sheet.getRange(row,3).setValue(messages[m].getBody());
With this:
// Print the message subject
sheet.getRange(row,3).setValue(getTextFromHtml(messages[m].getBody()));
The getTextFromHtml() function has been adapted from this answer, with the addition of handling for some basic formatting (numbered & bullet lists, paragraph breaks).
function getTextFromHtml(html) {
return getTextFromNode(Xml.parse(html, true).getElement());
}
var _itemNum; // Used to lead unordered & ordered list items.
function getTextFromNode(x) {
switch(x.toString()) {
case 'XmlText': return x.toXmlString();
case 'XmlElement':
var name = x.getName().getLocalName();
Logger.log(name);
var pre = '';
var post = '';
switch (name) {
case 'br':
case 'p':
pre = '';
post = '\n';
break;
case 'ul':
pre = '';
post = '\n';
itemNum = 0;
break;
case 'ol':
pre = '';
post = '\n';
_itemNum = 1;
break;
case 'li':
pre = '\n' + (_itemNum == 0 ? ' - ' : (' '+ _itemNum++ +'. '));
post = '';
break;
default:
pre = '';
post = '';
break;
}
return pre + x.getNodes().map(getTextFromNode).join('') + post;
default: return '';
}
}
From this answer: Google Apps Scripts - Extract data from gmail into a spreadsheet
You can forgo the getTextFromHTML function altogether by simply using getPlainBody(); instead of getBody();.

Categories

Resources