how to remove first 3 word in the sentence In javascript - javascript

How can I remove the first three words in java script when the response from the api I want to delete or remove the first three words.. the message from api is like below
"Error: GraphQL error: Account code already taken "
var temp = e.message
var temp1 = temp.map(function(f) {
return f.substring(temp.indexOf(' ') + 2);
});
console.log("Output", temp1)
expected output : " Account code already taken"

var st = "Error: GraphQL error: Account code already taken."
var s = st.split(' ')
s.splice(0,3)
st = s.join(' ');
console.log("Output", st)
Try this code

If the certain word like error: is present in the message then you can split the string with the word and return string from specific index:
var temp = "Error: GraphQL error: Account code already taken "
var temp1 = function(f) {
if(f.split('error:').length > 1)
return f.split('error:')[1].trim();
else return f;
};
console.log("Output:", temp1(temp))
Update: First, I will suggest you to fix the message format if possible. If you have to possible situation where the word in the message could be either error or error: then you can try the following:
var temp = "Error: GraphQL error Account code already taken "
var temp1 = function(f) {
var splitVal = 'error';
if(f.includes('error:'))
splitVal = 'error:';
if(f.split(splitVal).length > 1)
return f.split(splitVal)[1].trim();
else return f;
};
console.log("Output:", temp1(temp));

Create/modify the function to remove one word:
function removeOne(f) {
return f.substring(f.indexOf(' ') + 1);
}
and call it 3 times:
var temp1 = removeOne(removeOne(removeOne(temp)));
or in a loop:
var temp1 = temp;
for(var i = 0; i < 3; i++) {
temp1 = removeOne(temp1);
}
EDIT: wrapped the post into a snippet if someone had doubts:
var temp = "Error: GraphQL error: Account code already taken ";
/* Create/modify the function to remove one word: */
function removeOne(f) {
return f.substring(f.indexOf(' ') + 1);
}
/*and call it 3 times:*/
var temp1 = removeOne(removeOne(removeOne(temp)));
console.log("Output", temp1);
/*or in a loop:*/
temp1 = temp;
for(var i = 0; i < 3; i++) {
temp1 = removeOne(temp1);
}
console.log("Output", temp1);

const shorten = () => input.slice(21, input.length)

Related

count total number of word in pdf book using node js? [duplicate]

I wonder if is possible to get the text inside of a PDF file by using only Javascript?
If yes, can anyone show me how?
I know there are some server-side java, c#, etc libraries but I would prefer not using a server.
thanks
Because pdf.js has been developing over the years, I would like to give a new answer. That is, it can be done locally without involving any server or external service. The new pdf.js has a function: page.getTextContent(). You can get the text content from that. I've done it successfully with the following code.
What you get in each step is a promise. You need to code this way: .then( function(){...}) to proceed to the next step.
PDFJS.getDocument( data ).then( function(pdf) {
pdf.getPage(i).then( function(page){
page.getTextContent().then( function(textContent){
What you finally get is an string array textContent.bidiTexts[]. You concatenate them to get the text of 1 page. Text blocks' coordinates are used to judge whether newline or space need to be inserted. (This may not be totally robust, but from my test it seems ok.)
The input parameter data needs to be either a URL or ArrayBuffer type data. I used the ReadAsArrayBuffer(file) function in FileReader API to get the data.
Note: According to some other user, the library has updated and caused the code to break. According to the comment by async5 below, you need to replace textContent.bidiTexts with textContent.items.
function Pdf2TextClass(){
var self = this;
this.complete = 0;
/**
*
* #param data ArrayBuffer of the pdf file content
* #param callbackPageDone To inform the progress each time
* when a page is finished. The callback function's input parameters are:
* 1) number of pages done;
* 2) total number of pages in file.
* #param callbackAllDone The input parameter of callback function is
* the result of extracted text from pdf file.
*
*/
this.pdfToText = function(data, callbackPageDone, callbackAllDone){
console.assert( data instanceof ArrayBuffer || typeof data == 'string' );
PDFJS.getDocument( data ).then( function(pdf) {
var div = document.getElementById('viewer');
var total = pdf.numPages;
callbackPageDone( 0, total );
var layers = {};
for (i = 1; i <= total; i++){
pdf.getPage(i).then( function(page){
var n = page.pageNumber;
page.getTextContent().then( function(textContent){
if( null != textContent.bidiTexts ){
var page_text = "";
var last_block = null;
for( var k = 0; k < textContent.bidiTexts.length; k++ ){
var block = textContent.bidiTexts[k];
if( last_block != null && last_block.str[last_block.str.length-1] != ' '){
if( block.x < last_block.x )
page_text += "\r\n";
else if ( last_block.y != block.y && ( last_block.str.match(/^(\s?[a-zA-Z])$|^(.+\s[a-zA-Z])$/) == null ))
page_text += ' ';
}
page_text += block.str;
last_block = block;
}
textContent != null && console.log("page " + n + " finished."); //" content: \n" + page_text);
layers[n] = page_text + "\n\n";
}
++ self.complete;
callbackPageDone( self.complete, total );
if (self.complete == total){
window.setTimeout(function(){
var full_text = "";
var num_pages = Object.keys(layers).length;
for( var j = 1; j <= num_pages; j++)
full_text += layers[j] ;
callbackAllDone(full_text);
}, 1000);
}
}); // end of page.getTextContent().then
}); // end of page.then
} // of for
});
}; // end of pdfToText()
}; // end of class
I couldn't get gm2008's example to work (the internal data structure on pdf.js has changed apparently), so I wrote my own fully promise-based solution that doesn't use any DOM elements, queryselectors or canvas, using the updated pdf.js from the example at mozilla
It eats a file path for the upload since i'm using it with node-webkit.
You need to make sure you have the cmaps downloaded and pointed somewhere and you nee pdf.js and pdf.worker.js to get this working.
/**
* Extract text from PDFs with PDF.js
* Uses the demo pdf.js from https://mozilla.github.io/pdf.js/getting_started/
*/
this.pdfToText = function(data) {
PDFJS.workerSrc = 'js/vendor/pdf.worker.js';
PDFJS.cMapUrl = 'js/vendor/pdfjs/cmaps/';
PDFJS.cMapPacked = true;
return PDFJS.getDocument(data).then(function(pdf) {
var pages = [];
for (var i = 0; i < pdf.numPages; i++) {
pages.push(i);
}
return Promise.all(pages.map(function(pageNumber) {
return pdf.getPage(pageNumber + 1).then(function(page) {
return page.getTextContent().then(function(textContent) {
return textContent.items.map(function(item) {
return item.str;
}).join(' ');
});
});
})).then(function(pages) {
return pages.join("\r\n");
});
});
}
usage:
self.pdfToText(files[0].path).then(function(result) {
console.log("PDF done!", result);
})
Just leaving here a full working sample.
<html>
<head>
<script src="https://npmcdn.com/pdfjs-dist/build/pdf.js"></script>
</head>
<body>
<input id="pdffile" name="pdffile" type="file" />
<button id="btn" onclick="convert()">Process</button>
<div id="result"></div>
</body>
</html>
<script>
function convert() {
var fr=new FileReader();
var pdff = new Pdf2TextClass();
fr.onload=function(){
pdff.pdfToText(fr.result, null, (text) => { document.getElementById('result').innerText += text; });
}
fr.readAsDataURL(document.getElementById('pdffile').files[0])
}
function Pdf2TextClass() {
var self = this;
this.complete = 0;
this.pdfToText = function (data, callbackPageDone, callbackAllDone) {
console.assert(data instanceof ArrayBuffer || typeof data == 'string');
var loadingTask = pdfjsLib.getDocument(data);
loadingTask.promise.then(function (pdf) {
var total = pdf._pdfInfo.numPages;
//callbackPageDone( 0, total );
var layers = {};
for (i = 1; i <= total; i++) {
pdf.getPage(i).then(function (page) {
var n = page.pageNumber;
page.getTextContent().then(function (textContent) {
//console.log(textContent.items[0]);0
if (null != textContent.items) {
var page_text = "";
var last_block = null;
for (var k = 0; k < textContent.items.length; k++) {
var block = textContent.items[k];
if (last_block != null && last_block.str[last_block.str.length - 1] != ' ') {
if (block.x < last_block.x)
page_text += "\r\n";
else if (last_block.y != block.y && (last_block.str.match(/^(\s?[a-zA-Z])$|^(.+\s[a-zA-Z])$/) == null))
page_text += ' ';
}
page_text += block.str;
last_block = block;
}
textContent != null && console.log("page " + n + " finished."); //" content: \n" + page_text);
layers[n] = page_text + "\n\n";
}
++self.complete;
//callbackPageDone( self.complete, total );
if (self.complete == total) {
window.setTimeout(function () {
var full_text = "";
var num_pages = Object.keys(layers).length;
for (var j = 1; j <= num_pages; j++)
full_text += layers[j];
callbackAllDone(full_text);
}, 1000);
}
}); // end of page.getTextContent().then
}); // end of page.then
} // of for
});
}; // end of pdfToText()
}; // end of class
</script>
Here's some JavaScript code that does what you want using Pdf.js from http://hublog.hubmed.org/archives/001948.html:
var input = document.getElementById("input");
var processor = document.getElementById("processor");
var output = document.getElementById("output");
// listen for messages from the processor
window.addEventListener("message", function(event){
if (event.source != processor.contentWindow) return;
switch (event.data){
// "ready" = the processor is ready, so fetch the PDF file
case "ready":
var xhr = new XMLHttpRequest;
xhr.open('GET', input.getAttribute("src"), true);
xhr.responseType = "arraybuffer";
xhr.onload = function(event) {
processor.contentWindow.postMessage(this.response, "*");
};
xhr.send();
break;
// anything else = the processor has returned the text of the PDF
default:
output.textContent = event.data.replace(/\s+/g, " ");
break;
}
}, true);
...and here's an example:
http://git.macropus.org/2011/11/pdftotext/example/
Note: This code assumes you're using nodejs. That means you're parsing a local file instead of one from a web page since the original question doesn't explicitly ask about parsing pdfs on a web page.
#gm2008's answer was a great starting point (please read it and its comments for more info), but needed some updates (08/19) and had some unused code. I also like examples that are more full. There's more refactoring and tweaking that could be done (e.g. with await), but for now it's as close to that original answer as it could be.
As before, this uses Mozilla's PDFjs library. The npmjs package is at https://www.npmjs.com/package/pdfjs-dist.
In my experience, this doesn't do well in finding where to put spaces, but that's a problem for another time.
[Edit: I believe the update to the use of .transform has restored the whitespace as it originally behaved.]
// This file is called myPDFfileToText.js and is in the root folder
let PDFJS = require('pdfjs-dist');
let pathToPDF = 'path/to/myPDFfileToText.pdf';
let toText = Pdf2TextObj();
let onPageDone = function() {}; // don't want to do anything between pages
let onFinish = function(fullText) { console.log(fullText) };
toText.pdfToText(pathToPDF, onPageDone, onFinish);
function Pdf2TextObj() {
let self = this;
this.complete = 0;
/**
*
* #param path Path to the pdf file.
* #param callbackPageDone To inform the progress each time
* when a page is finished. The callback function's input parameters are:
* 1) number of pages done.
* 2) total number of pages in file.
* 3) the `page` object itself or null.
* #param callbackAllDone Called after all text has been collected. Input parameters:
* 1) full text of parsed pdf.
*
*/
this.pdfToText = function(path, callbackPageDone, callbackAllDone) {
// console.assert(typeof path == 'string');
PDFJS.getDocument(path).promise.then(function(pdf) {
let total = pdf.numPages;
callbackPageDone(0, total, null);
let pages = {};
// For some (pdf?) reason these don't all come in consecutive
// order. That's why they're stored as an object and then
// processed one final time at the end.
for (let pagei = 1; pagei <= total; pagei++) {
pdf.getPage(pagei).then(function(page) {
let pageNumber = page.pageNumber;
page.getTextContent().then(function(textContent) {
if (null != textContent.items) {
let page_text = "";
let last_item = null;
for (let itemsi = 0; itemsi < textContent.items.length; itemsi++) {
let item = textContent.items[itemsi];
// I think to add whitespace properly would be more complex and
// would require two loops.
if (last_item != null && last_item.str[last_item.str.length - 1] != ' ') {
let itemX = item.transform[5]
let lastItemX = last_item.transform[5]
let itemY = item.transform[4]
let lastItemY = last_item.transform[4]
if (itemX < lastItemX)
page_text += "\r\n";
else if (itemY != lastItemY && (last_item.str.match(/^(\s?[a-zA-Z])$|^(.+\s[a-zA-Z])$/) == null))
page_text += ' ';
} // ends if may need to add whitespace
page_text += item.str;
last_item = item;
} // ends for every item of text
textContent != null && console.log("page " + pageNumber + " finished.") // " content: \n" + page_text);
pages[pageNumber] = page_text + "\n\n";
} // ends if has items
++self.complete;
callbackPageDone(self.complete, total, page);
// If all done, put pages in order and combine all
// text, then pass that to the callback
if (self.complete == total) {
// Using `setTimeout()` isn't a stable way of making sure
// the process has finished. Watch out for missed pages.
// A future version might do this with promises.
setTimeout(function() {
let full_text = "";
let num_pages = Object.keys(pages).length;
for (let pageNum = 1; pageNum <= num_pages; pageNum++)
full_text += pages[pageNum];
callbackAllDone(full_text);
}, 1000);
}
}); // ends page.getTextContent().then
}); // ends page.then
} // ends for every page
});
}; // Ends pdfToText()
return self;
}; // Ends object factory
Run in the terminal:
node myPDFfileToText.js
Updated 02/2021
<script src="https://npmcdn.com/pdfjs-dist/build/pdf.js"></script>
<script>
function Pdf2TextClass(){
var self = this;
this.complete = 0;
this.pdfToText = function(data, callbackPageDone, callbackAllDone){
console.assert( data instanceof ArrayBuffer || typeof data == 'string' );
var loadingTask = pdfjsLib.getDocument(data);
loadingTask.promise.then(function(pdf) {
var total = pdf._pdfInfo.numPages;
//callbackPageDone( 0, total );
var layers = {};
for (i = 1; i <= total; i++){
pdf.getPage(i).then( function(page){
var n = page.pageNumber;
page.getTextContent().then( function(textContent){
//console.log(textContent.items[0]);0
if( null != textContent.items ){
var page_text = "";
var last_block = null;
for( var k = 0; k < textContent.items.length; k++ ){
var block = textContent.items[k];
if( last_block != null && last_block.str[last_block.str.length-1] != ' '){
if( block.x < last_block.x )
page_text += "\r\n";
else if ( last_block.y != block.y && ( last_block.str.match(/^(\s?[a-zA-Z])$|^(.+\s[a-zA-Z])$/) == null ))
page_text += ' ';
}
page_text += block.str;
last_block = block;
}
textContent != null && console.log("page " + n + " finished."); //" content: \n" + page_text);
layers[n] = page_text + "\n\n";
}
++ self.complete;
//callbackPageDone( self.complete, total );
if (self.complete == total){
window.setTimeout(function(){
var full_text = "";
var num_pages = Object.keys(layers).length;
for( var j = 1; j <= num_pages; j++)
full_text += layers[j] ;
console.log(full_text);
}, 1000);
}
}); // end of page.getTextContent().then
}); // end of page.then
} // of for
});
}; // end of pdfToText()
}; // end of class
var pdff = new Pdf2TextClass();
pdff.pdfToText('PDF_URL');
</script>
For all the people who actually want to use it on a node server:
/**
* Created by velten on 25.04.16.
*/
"use strict";
let pdfUrl = "http://example.com/example.pdf";
let request = require('request');
var pdfParser = require('pdf2json');
let pdfPipe = request({url: pdfUrl, encoding:null}).pipe(pdfParser);
pdfPipe.on("pdfParser_dataError", err => console.error(err) );
pdfPipe.on("pdfParser_dataReady", pdf => {
//optionally:
//let pdf = pdfParser.getMergedTextBlocksIfNeeded();
let count1 = 0;
//get text on a particular page
for (let page of pdf.formImage.Pages) {
count1 += page.Texts.length;
}
console.log(count1);
pdfParser.destroy();
});
It is possible but:
you would have to use the server anyway, there's no way you can get content of a file on user computer without transferring it to server and back
I don't thing anyone has written such library yet
So if you have some free time you can learn pdf format and write such a library yourself, or you can just use server side library of course.

class inheritance in javascript/angular

I am working on my hello world project. I have two pages let's call them "configuration" and "add configuration" *.html. Each one has its own controller like this:
angular.module('MissionControlApp').controller('ConfigController', ConfigController);
angular.module('MissionControlApp').controller('AddConfigController', AddConfigController);
Now, each controller has some properties that very much overlap:
function ConfigController($routeParams, ConfigFactory, $window){
var vm = this;
vm.status;
vm.projectId = $routeParams.projectId;
vm.selectedProject;
vm.configurations;
vm.selectedConfig;
vm.selectedRecords;
vm.filteredConfig;
vm.newFile;
vm.fileWarningMsg = '';
vm.addFile = function(){
var filePath = vm.newFile;
var encodedUri = encodeURIComponent(filePath);
vm.fileWarningMsg='';
ConfigFactory
.getByEncodedUri(encodedUri).then(function(response){
var configFound = response.data;
var configNames = '';
var configMatched = false;
if(response.status === 200 && configFound.length > 0){
//find an exact match from text search result
for(var i = 0; i < configFound.length; i++) {
var config = configFound[i];
for(var j=0; j<config.files.length; j++){
var file = config.files[j];
if(file.centralPath.toLowerCase() === filePath.toLowerCase()){
configMatched = true;
configNames += ' [' + config.name + '] ';
break;
}
}
}
}
if(configMatched){
vm.fileWarningMsg = 'Warning! File already exists in other configurations.\n' + configNames;
} else if(filePath.length > 0 && filePath.includes('.rvt')){
var file1 = { centralPath: filePath };
vm.selectedConfig.files.push(file1);
vm.newFile = '';
} else{
vm.fileWarningMsg = 'Warning! Please enter a valid file.';
}
}, function(error){
vm.status = 'Unable to get configuration data: ' + error.message;
});
};
My AddConfigController also wants to have the same functionality for addFile() so I just copy pasted the same code, but coming from C# i am sure i can do some class inheritance here, and just inherit from ConfigController and extend...right?
If this is super noob question. then apologies. js is a bit of a mystery to me.
function AddConfigController($routeParams, ConfigFactory, $window){
var vm = this;
vm.status;
vm.projectId = $routeParams.projectId;
vm.selectedProject = {};
vm.newConfig = {};
vm.newFile;
vm.fileWarningMsg = '';
vm.addFile = function(){
var filePath = vm.newFile;
var encodedUri = encodeURIComponent(filePath);
vm.fileWarningMsg='';
ConfigFactory
.getByEncodedUri(encodedUri).then(function(response){
var configFound = response.data;
var configNames = '';
var configMatched = false;
if(response.status === 200 && configFound.length > 0){
//find an exact match from text search result
for(var i = 0; i < configFound.length; i++) {
var config = configFound[i];
for(var j=0; j<config.files.length; j++){
var file = config.files[j];
if(file.centralPath.toLowerCase() === filePath.toLowerCase()){
configMatched = true;
configNames += ' [' + config.name + '] ';
break;
}
}
}
}
if(configMatched){
vm.fileWarningMsg = 'Warning! File already exists in other configurations.\n' + configNames;
} else if(filePath.length > 0 && filePath.includes('.rvt')){
var file1 = { centralPath: filePath };
vm.selectedConfig.files.push(file1);
vm.newFile = '';
} else{
vm.fileWarningMsg = 'Warning! Please enter a valid file.';
}
}, function(error){
vm.status = 'Unable to get configuration data: ' + error.message;
});
};
Since you asked about inheritance and you appear to be using ECMAScript 5, let me suggest taking a look at Object.create(). Specifically, the classical inheritance example.
That said, in AngularJS, a better solution would be to create a Service that manages files or configurations and put the addFile function in there. That way, both controllers could inject the service and call the same function when it is time to add a file. Likewise, other services and controllers that may need access to this functionality could inject it as well.

Elements will not add to Javascript array

I'm trying to load in two txt files and compare the differences between the two. More specifically I'm looping through one file per line and comparing it to every line in another txt file.
For the most part everything is working but I have found that I'm only able to access the array within the lr.on('line') function. However I have declared the array in the global scope.
Here is the code:
var LineByLineReader = require('line-by-line');
var lr = new LineByLineReader('phones.txt');
var lr2 = new LineByLineReader('wor.txt');
var phoneArray = [];
var worArray = [];
lr.on('error', function(err){
if(err){
console.log("We have found the following error: " + err);
}
});
lr2.on('error', function(err){
if(err){
console.log("We have found the following error: " + err);
}
});
lr.on('line', function(line){
phoneArray.push(line);
});
lr2.on('line', function(line){
worArray.push(line);
});
for(var i = 0; i < phoneArray.length; i++){
for(var x = 0; x < worArray.length; x++){
if(array1[i] === array2[x]){
console.log("Found Match: " + array2[x]);
}
}
}
Maybe you just forgot to use the right variables names inside your for loop?
And you just need this? :
if(phoneArray[i] === worArray[x]){
console.log("Found Match: " + worArray[x]);

javascript, exception for string/object manipulation

So, I have to functions to turn a string to an object and an object to a string, however I need to account for an except and I am not sure how. Let me show you what I have
parseObjectToUrl: function (obj){
var myStr = "";
var first_iteration = true;
for (var p in obj) {
if(first_iteration){
myStr += p + "=";
first_iteration = false;
}else{
myStr += "&" + p + "=";
}
tObj = obj[p];
var first_inner = true;
for(t in tObj){
if(first_inner){
myStr += t;
first_inner = false;
}else{
myStr += "," + t;
}
yObj = tObj[t];
for( y in yObj){
myStr += "/" + yObj[y];
}
}
}
return myStr;
},
parseObjectFromUrl : function(url){
var builtObj = {};
//remove first slash
url = url.slice(0, 0) + url.slice(1);
var ch = url.split('&');
var tempParent = {};
for (var p in ch) {
var tempSub = {};
var arr = ch[p].split('=');
var keyParent = arr[0];
var splitInside = arr[1].split(",");
for (var i in splitInside) {
var sub = splitInside[i].split('/');
var subKey = sub[0];
tempSub[subKey] = sub.slice(1);
}
tempParent[keyParent] = tempSub;
}
return tempParent
}
So these the string looks like
/module1=mod1/2/3/4,mod2/2/3/4&module2=mod2/3/4/5
and the object looks like
myObj =
{
module1 : { mod1 : [2,3,4] , mod2 [2,3,4]} ,
module2 : { mod2 : [3,4,5]}
}
So these functions work fine for me however I (unfortunately) need to be able to handle the case when the user adds an "/" into the options like -
myObj =
{
module1 : { mod1 : [2/,3/,4/] , mod2 [2,3,4]} ,
module2 : { mod2 : [3,4,5]}
}
I'm sure it's going to throw a wrench in my function because i'm splitting by the "/", so I'm not sure how to get around this. Would i escape the slash? How would that fit into the functions if so? Looking for any advice on this issue. Thanks!
Edit:
I was able to encode the escaped url like :
obj.replace(/([/-])/g, "%2F");
to an escaped url, hoever I am having trouble doing the reverse of this. here is my attempt.
obj.replace(/(%2F)/g, "/");
in my opinion it would be better to use url arrays, but keep in mind the characters for your url could be limited:
maximum length of HTTP GET request?
having said that one could do something like this:
module1[]=1&module1[]=2&module2[]=4&module2[]=3
this is equal to the following pseudo code:
$_GET["module1"] = array(1,2);
$_GET["module2"] = array(4,3);
and use encodeURIComponent & decodeURIComponent for your values
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

For loop going out of range? [duplicate]

This question already has answers here:
What is an off-by-one error and how do I fix it?
(6 answers)
Closed 4 months ago.
I am using a library in Javascript to pull in data from a chat server. The library is irrelevant but is quickblox. The data comes back into my app and can be seen, but when I try an loop on an object they return, it goes out of range, can't get 'last_message' of undefined. Loop should run for res.items[i].length which at the mo is two, but it is trying to carry on running, it seems.
var onDialogs = function(err, res){
console.log("------------------------------------List Of Dialogs------------------------------------",res);
var count = 0;
var sent;
var i = 0;
console.log("res.items.length",res.items.length)
for (i;i<=res.items.length;i++){
console.log("this one: ", res.items[i]);
if (res.items[i].last_message===null||res.items[i].last_message===undefined||res.items[i].last_message===""){
alert("SOMETHING WENT WRONG");
}
else{
console.log("RES.ITEMS: ", res.items);
console.log("RES ITEMS LEN", res.items.length);
console.log("***********************I IS SET TO: ",i," *******************************************");
console.log("RAWR",res.items);
console.log(res.items[i].last_message_date_sent,res.items[i].last_message);
console.log(res.items[i]);
if (res.items[i].last_message === undefined || res.items[i].last_message===null || res.items[i].last_message===""){
console.log("FAIL");
}
else{
var dialogID = res.items[i]._id;
var sent = res.items[i].created_at;
console.log(res.items[i].created_at);
var year = sent.substring(0,4);
var month = sent.substring(5,7);
var day = sent.substring(8,10);
var userIDInChat;
var j =0;
userArray=[];
var userArray = res.items[i].occupants_ids;
console.log("USER ARRAY: ",userArray);
for (j; j<userArray.length; j++){
console.log(userArray[j]);
var testID = window.localStorage.getItem("userID");
console.log("USERARRAY[j]", userArray[j]);
if (userArray[j] != testID){
console.log("INSIDE THE IF STATEMENT");
userIDInChat = userArray[j];
window.localStorage.setItem("userIDInChat", userIDInChat);
console.log("//*******BLOCK ID SET TO********\\", userIDInChat, testID, res);
$.get("http://www.domain.co.uk/API/getUserByID.php", { userID: userIDInChat}, function (data) {
console.log("API CALL:",data);
chatOpponent = data;
console.log(chatOpponent);
console.log("------------------------------------------------------------------------------------------");
renderBlock(res,j,i,chatOpponent,userIDInChat,userArray,testID,day,month,year,dialogID);
});
}
}
}
}
}
//End block
};
function renderBlock(res,j,i,chatOpponent,userIDInChat,userArray,testID,day,month,year,dialogID){
console.log("(res,j,i,chatOpponent,userIDInChat,userArray,testID)");
console.log("RENDERBLOCK PARAMS: ",res,j,i,chatOpponent,userIDInChat,userArray,testID);
//insert function here
console.log("RES: ",res);
var senderID = userIDInChat;
//compare date - vs. moment - today, yesterday or date
sent = day + "/" + month + "/" + year;
console.log(sent);
var onMessages = function(err,result){
window.localStorage.setItem("RESULTTEST",result);
console.log("ONMESSAGESRESULTHERE",err,result);
//console.log("---------onMessages---------",result.items[i].date_sent);s
};
var msgList = QB.chat.message.list({chat_dialog_id: dialogID}, onMessages);
var messages;
console.log(messages);
if (res.items[i].last_message.length>=140) {
var last_message = res.items[i].last_message.substring(0,140)+".....";
}
else{
var last_message = res.items[i].last_message;
}
var readFlag = res.items[i].read;
console.log("SENDERID:", senderID, "username: ", chatOpponent, "last_message", last_message, "sentFlag");
if (readFlag === 1){
var read = "fa-envelope-o";
}
else {
var read = "fa-envelope";
}
var html = "<div class='messageBlock' id='"+senderID+"'><div style='width:10%;min-height:64px;float:left;'><i class='fa '"+read+"'></i><p>"+sent+"</p></div><div style='width:90%;min-height:64px;float:right;'><p class='user'><b><i>"+chatOpponent+"</b></i></p><p>"+last_message+"</p></div></div>";
Object being looped on:
Object {total_entries: 2, skip: 0, limit: 50, items: Array[2]}items: Array[2]0: Object_id: "54e4bd3929108282d4072a37"created_at: "2015-02-18T16:26:33Z"last_message: "test"last_message_date_sent: 1425640757last_message_user_id: 2351789name: nulloccupants_ids: Array[2]photo: nulltype: 3unread_messages_count: 0user_id: 2351781xmpp_room_jid: null__proto__: Object1: Object_id: "54ec990f29108282d40b19e2"created_at: "2015-02-24T15:30:23Z"last_message: "herro!"last_message_date_sent: 1424858692last_message_user_id: 2394026name: nulloccupants_ids: Array[2]photo: nulltype: 3unread_messages_count: 0user_id: 2351789xmpp_room_jid: null__proto__: Objectlength: 2__proto__: Array[0]limit: 50skip: 0total_entries: 2__proto__: Object
for (i;i<=res.items.length;i++){
should be
for (i;i<res.items.length;i++){
Simple you are looping one too many times.
for (i;i<=res.items.length;i++){
^^
arrays are zero index so that means that last index is the length minus one.
for (i;i<res.items.length;i++){
^^

Categories

Resources