Displaying current & total page number N(N) - javascript

I am new to Javascript,so forgive my silly mistakes in advance.
I have a requirement where I have to print current and total page number excluding even pages which are blank.
Example : For 5 page long document,it should display like:
1(3)
2(3)
3(3)
Any sort of info is welcome since I am in dire need of this code to work.
I have tried this but it doesn't work:
var current_page=0 ;
var total_pages=0;
if((current_page<total_pages)||(current_page=total_pages))
{
current_page++;
if(current_page % 2!==0)
{
total_pages++;
}
}
Also, this one too doesn't worked :(
var temp = (this.pageNum) + "(" + (this.numPages) + ")" ;

You have a logical error here:
current_page = total_pages // Note single = symbol between.
You are assigning instead of comparing. Please use == to compare:
current_page == total_pages
Or === for strict comparison as the type of both the variables is same.

Does that help?
function (totalPages, currentPage)
{
if (currentPage%2==1) return "";
var tp = parseInt(totalPages/2+1);
var cp = parseInt(currentPage/2+1);
return "" + cp + "(" + tp + ")";
}

Related

Print 42 characters on each line from string

Problem: I'm using qzTray to print a receipt, earlier i was using html format but the print quality was not good. so i shifted to JavaScript and wrote bunch of functions to print the receipt, i am using this function to print 42 character on each line, i have a string of 105 characters, the string will be printed in 3 lines. I've written some code but its not working entirely, can anyone give me a hint how to do this ?
first line is printed fine but from second line and onward the substr looks like its not working, i don't know why.
Thanks is advance.
window.const_alignLeft = '\x1B\x61\x30';
window.const_newLine = '\x0A';
function getItemRowFull(itemTitle, itemPrice = null) {
var totalColsPerPage = 42;
var leftCols = 35;
var marginSpace = totalColsPerPage === 48 ? '' : ' ';
if(itemTitle.length > leftCols) {
leftCols = (!itemPrice) ? totalColsPerPage : leftCols;
let itemTitleLength = itemTitle.length;
let receipt = '';
let startFrom = 0;
let remainingCharacters = itemTitle.length;
while (startFrom < itemTitleLength) {
receipt += const_alignLeft + marginSpace + itemTitle.substr(startFrom, startFrom + leftCols);
receipt += const_newLine;
remainingCharacters = (remainingCharacters + itemTitleLength) - (itemTitleLength + leftCols);
startFrom = (startFrom + leftCols);
}
return receipt;
}
}
Image In the image below the function will be used to paragraph related to notes.

How to Validate a Phone Number Using Parentheses in Javascript

I am fairly new to coding, especially Javascript, and am having difficulty getting my form to recognize phone numbers using parentheses. I have been able to make a code for accepting dashes between numbers to work, but the variations I have attempted with parentheses have all come back as invalid. Below is my functioning code with dashes. If possible, I was hoping to get some advice for how to adjust this code to incorporate parentheses. I am attempting to make the form function so that it can accept the following variations: xxx-xxx-xxxx , (xxx)xxxxxxx , and (xxx)xxx-xxxx.
function validateTenDigitsAndDashes (str)
{
//alert("in validateTenDigitsAndDashes: str, str.length = '" + str + "', " + str.length) ;
var retVal = 12 == str.length ;
for (var i = 0 ; retVal && (i < str.length) ; i++) {
//alert(" in loop: i, str.charAt(i) = " + i + ", " + str.charAt(i)) ;
if (3 == i || 7 == i) retVal = '-' == str.charAt(i)
else retVal = isDigit(str.charAt(i)) ;
}
return retVal ;
}
Hope it may help you.
function telephoneCheck(str) {
var a = /^(1\s|1|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3})(\-|\s)?(\d{4})$/.test(str);
alert(a);
}
//call function to check
telephoneCheck("(555) 555-5555");
Answer picked from below link on stackoverflow.
Validating Phone Numbers Using Javascript
A small regex like this would do the trick ^\(?\d{3}\)?-?\d{3}-?\d{4}$

is there something wrong with my if statement?

I am checking the number of wrong lines with a for loop
var lines = dateinput.value.split(/\r?\n/);
var wrongLines ="";
for(var i = 0; i<lines.length ; i++){
if (lines[i].match(regex) == null) {
wrongLines += i + 1 +",";
}
and I want to add different alerts for the number of the wrong lines
if (i = 1 ) {
alert('The date on line ' + wrongLines + ' is invalid. Please enter a valid date formatted DD/MM/YYYY');
}
else if (i > 1 ) {
alert('Dates on line ' + wrongLines + ' are invalid. Please enter a valid date formatted DD/MM/YYYY');
}
but it does not works - every time I get the first alert
Try like this
if (i == 1 )
You are assigning values instead of comparing.
N.B. :
= means assigning
== means comparing
=== means strict comparing
at first impression, you should replace if (i = 1) with if (i == 1)

Javascript to reduce line breaks to two?

I'm using the following javascript:
if (theSelection)
{
for (var i = 0, l = theSelection.length; i < l; i++)
{
if (theSelection[i] == '[' && theSelection[i+1] == 'q') level++;
if (theSelection[i-6] == 'q' && theSelection[i-7] == '/' && theSelection[i-8] == '[') level--;
if (level<1) tmp.push(theSelection[i]);
}
theSelection = tmp.join('');
}
... to remove nested quotes from text before it is sent to a reply box, but it leaves behind line breaks in place of the purged nested quotes. So, for instance, if I quote a post from User 1 which says...
Text.
[quote="User 2"]Quote text.[/quote]
More text.
It shows up in the reply box as...
[quote="User 1"]Text.
More text.[/quote]
What would I add to this javascript to either remove this space or limit the space between new lines to just two line breaks, so that the final text displayed in the reply box appears as:
[quote="User 1"]Text.
More text.[/quote]
Thanks for any help.
EDIT:
Here's a larger bit of the code:
if (theSelection)
{
for (var i = 0, l = theSelection.length; i < l; i++)
{
if (theSelection[i] == '[' && theSelection[i+1] == 'q') level++;
if (theSelection[i-6] == 'q' && theSelection[i-7] == '/' && theSelection[i-8] == '[') level--;
if (level<1) tmp.push(theSelection[i]);
}
theSelection = tmp.join('');
}
if (theSelection)
{
if (bbcodeEnabled)
{
insert_text('[quote="' + username + '"]' + '\n' + '\n' + theSelection + '[/quote]' + '\n' + '\n');
}
else
{
insert_text(username + ' ' + l_wrote + ':' + '\n');
var lines = split_lines(theSelection);
for (i = 0; i < lines.length; i++)
{
insert_text('> ' + lines[i] + '\n');
}
}
}
I placed...
if (theSelection)
{
theSelection = theSelection.replace(/\n{2,}/g, "\n\n");
}
... between the two existing "if (theSelection)" statements, and it worked great. One remaining issue though. The nested quote removal happens before the quoted text is placed within its own quote tags, and two line breaks are added after the opening quote tag. So if a quoted post contained a nested quote before any original text, then the text that the above code generates has four line breaks at the opening instead of the intended two. So I think I would need to place...
if (theSelection)
{
theSelection = theSelection.replace(/\n{2,}/g, "\n\n");
}
... after theSelection is inserted within its own quote tags, at which point "if (theSelection)" seems to no longer work, and I'm so new to javascript that I don't know how to replace "theSelection" with something that will reflect the output of the previous "if (theSelection)" statement. I hope that made at least a little sense.
Use a RegExp. The following code will replace 2+ new lines by two newlines.
string = string.replace(/\n{2,}/g, "\n\n")
I recommend to show a sign that notifies the reader of the fact that a quote has disappeared. Consider the following:
Post 50 by userA: My fish died =(
============================
Post 51 by userB:
[quote=Niceidea]
(2 pages ago) What about blabla. ...
[/quote]
Awesome!
============================
After applying your code:
============================
Post 50 by userA: My fish died =(
============================
Post 51 by userB: Awesome!
============================
The previous poster might be offended, because he didn't know the context of the reply.
I have figured out a nice solution: less code and exactly the thing you wanted:
var output,
theSelection = 'Text.\n\n[quote="User 2"]\nQuote tex\nt.\n[/quote]\n\n\n\n\nMore text.';
/*
* theSelection is:
* 'Text.
*
* [quote="User 2"]
* Quote tex
* t.
* [/quote]
*
*
*
* More text.'
*/
if (theSelection) {
output = theSelection.replace(/\[quote=".*"\][\s\S]*\[\/quote\]/gi, '')
.replace(/\n{2,}/g, '\n\n');
}
console.log(output);
/*
* Outputs:
* 'Text.
*
* More text.'
*
*/

Converting VBScript to Javascript, What is the right way of parsing source code?

I was asked to convert some VB6/VBScript code to javascript so after googling it and not finding anything I can use,I wrote a small javascript function to help me do the conversion; it's so crude and only converts (some of) the synatx, but it worked for me for the job I had...now I'm thinking of improving it but the method I used is so primitive (Regular Expression matching and replacing).
So...my question is:
What is the proper way to parse source code? is there any (not so complicated) way of doing it? and I don't want to use Exe's, it must be done entirely in Javascript. I'm not searching for ready-to-use source code (I don't think it exists!) but I want to learn how to be able to start with source code and turn it into objects (the opposite of serialization, I think?).
//here is the code:
var strs=[];
function vbsTojs(vbs){
var s = vbs;
s = HideStrings(s);
//only function block
s = s.match(/Function[\w\W]+End\s+Function/gim)[0];
//line-continuation char
s = s.replace(/_\n/gm,"");
//replace ":" with CRLF
s = s.replace(/:/gm,"\n");
//move inline comment to its own line
s = s.replace(/^(.+)'(.*)$/gim,"'$2\n$1");
//single line if -> multiple line
s = s.replace(/\bthen\b[ \t](.+)/gi,"then\n$1\nEnd If");
//alert(s);
var Vars='';
var Fx='';
var FxHead='';
var Args = '';
a=s.split('\n');
//trim
for(i=0;i<a.length;i++){
a[i]=a[i].replace(/^\s+|\s+$/,"");
}
//remove empty items
a=a.filter(function(val) { return val !== ""; });
//alert(a.join('\n'));
//function
a[0]=a[0].replace(/function\s+/i,"");
Fx = a[0].match(/^\w+/)[0];
a[0]=a[0].replace(Fx,"").replace(/[\(\)]/g,"");
a[0]=a[0].replace(/\bbyval\b/gi,"").replace(/\bbyref\b/gi,"").replace(/\boptional\b/gi,"");
a[0]=a[0].replace(/\bas\s+\w+\b/gi,"");
a[0]=a[0].replace(/\s+/g,"");
a[0]=a[0].replace(/,/gi,", ");
FxHead = "function " + Fx+ " ("+ a[0] + "){";
a[0]="";
//end function
a.length = a.length-1;
for(i=1;i<a.length;i++){
//Vars
if(a[i].search(/^dim\s+/i)>-1){
a[i]=a[i].replace(/dim\s*/i,"");
Vars += a[i] + ",";
a[i]='';
//FOR
}else if(a[i].search(/^\bFOR\b\s+/i)>-1){
a[i]=a[i].replace(/^\bFOR\b\s+/i,"");
counter = a[i].match(/^\w+/)[0];
from = a[i].match(/=\s*[\w\(\)]+/)[0];
from=from.replace(/=/,"").replace(/\s+/g,"");
a[i]=a[i].replace(counter,"").replace(from,"").replace(/\bTO\b/i,"");
to = a[i].match(/\s*[\w\(\)]+\s*/)[0];
to=to.replace(/=/,"").replace(/\s+/g,"");
a[i] = "for(" + counter + "=" + from + "; " + counter + "<=" + to + "; " + counter + "++){"
//NEXT
}else if(a[i].search(/^NEXT\b/i)>-1){
a[i] = "}";
//EXIT FOR
}else if(a[i].search(/\bEXIT\b\s*\bFOR\b/i)>-1){
a[i] = "break";
//IF
}else if(a[i].search(/^\bIF\b\s+/i)>-1){
a[i]=a[i].replace(/^\bIF\b\s+/i,"");
a[i]=a[i].replace(/\bTHEN$\b/i,"");
a[i]=a[i].replace(/=/g,"==").replace(/<>/g,"!="); //TODO: it should not replace if inside a string! <---------------
a[i]=a[i].replace(/\bOR\b/gi,"||").replace(/\bAND\b/gi,"&&"); //TODO: it should not replace if inside a string! <---------------
a[i] = "if(" + a[i] + "){";
//ELSE
}else if(a[i].search(/^ELSE/i)>-1){
a[i] = "}else{";
//END IF
}else if(a[i].search(/^END\s*IF/i)>-1){
a[i] = "}";
//WHILE
}else if(a[i].search(/^WHILE\s/i)>-1){
a[i] = a[i].replace(/^WHILE(.+)/i,"while($1){");
//WEND
}else if(a[i].search(/^WEND/i)>-1){
a[i] = "}";
//DO WHILE
}else if(a[i].search(/^DO\s+WHILE\s/i)>-1){
a[i] = a[i].replace(/^DO\s+WHILE(.+)/i,"while($1){");
//LOOP
}else if(a[i].search(/^LOOP$/i)>-1){
a[i] = "}";
//EXIT FUNCTION
}else if(a[i].search(/\bEXIT\b\s*\bFUNCTION\b/i)>-1){
a[i] = "return";
//SELECT CASE
}else if(a[i].search(/^SELECT\s+CASE(.+$)/i)>-1){
a[i]=a[i].replace(/^SELECT\s+CASE(.+$)/i,"switch($1){");
}else if(a[i].search(/^END\s+SELECT/i)>-1){
a[i] = "}";
}else if(a[i].search(/^CASE\s+ELSE/i)>-1){
a[i] = "default:";
}else if(a[i].search(/^CASE[\w\W]+$/i)>-1){
a[i] = a[i] + ":" ;
}
//CONST
else if(a[i].search(/^CONST/i)>-1){
a[i] = a[i].replace(/^CONST/i,"const");
}
else{
//alert(a[i]);
}
//COMMENT
if(a[i].search(/^\'/)>-1){
a[i]=a[i].replace(/^\'/,"//");
}else if(a[i].search(/\'.*$/)>-1){
a[i]=a[i].replace(/\'(.*)$/,"//$1");
}
}
//alert(a.join("*"));
Vars = Vars.replace(/\s*AS\s+\w+\s*/gi,"");
if(Vars!="") Vars = "var " + Vars.replace(/,$/,";").replace(/,/g,", ");
FxHead + '\n' + Vars;
a=a.filter(function(val) { return val !== ""; }) //remove empty items
for(i=0;i<a.length;i++){
if (a[i].search(/[^}{:]$/)>-1) a[i]+=";";
}
ss = FxHead + '\n' + Vars + '\n' + a.join('\n') + '\n}';
ss = ss.replace(new RegExp(Fx+"\\s*=\\s*","gi"),"return ");
ss = UnHideStrings(ss);
return jsIndenter(ss);
}
//-----------------------------------------------------
function jsIndenter(js){
var a=js.split('\n');
var margin=0;
var s = '';
//trim
for(i=0;i<a.length;i++){ a[i]=a[i].replace(/^\s+|\s+$/,""); }
//remove empty items
a=a.filter(function(val) { return val !== ""; });
for(var i=1;i<a.length;i++){
if(a[i-1].indexOf("{")>-1) margin += 4 ;
if(a[i].indexOf("}")>-1) { margin -= 4; }
if(margin<0) margin = 0;
a[i] = StrFill(margin," ") + a[i] ;
}
return a.join('\n');
}
function StrFill(Count,StrToFill){
var objStr,idx;
if(StrToFill=="" || Count==0){
return "";
}
objStr="";
for(idx=1;idx<=Count;idx++){
objStr += StrToFill;
}
return objStr;
}
function HideStrings(text){
const x = String.fromCharCode(7);
const xxx = String.fromCharCode(8);
text = text.replace(/"""/gim, '"'+xxx); //hide 3 quotes " " "
var idx=0, f=0;
while(f>-1){
f = text.search(/".+?"/gim);
if(f>-1){
strs.push(text.match(/".+?"/)[0]);
//alert(strs[idx]);
text = text.replace(/".+?"/, x+idx+x);
idx++;
}
}
//alert(text);
return text;
}
function UnHideStrings(text){
for(var i=0; i<strs.length; i++){
text = text.replace(new RegExp("\\x07"+i+"\\x07"), strs[i]);
}
//Unhide 3 quotes " " " ***BUG: causes unterminated string if triple-quotes are at the end of the string
text = text.replace(/\x08/gim,'\\"');
text = text.replace(/""/gi,'\\"');
return text;
}
The proper way to parse source code for any programming language is to use a parser. Regular expressions are a useful part of (some) parsers, but a parser is a different sort of thing. There is quite a body of research and techniques in the Computer Science literature on the subject of parsing, and it's a fascinating pursuit to study.
"Converting" a bunch of Visual Basic code to Javascript is a project that seems inherently fraught with peril and mystery. A Visual Basic parser will be just the first significant hurdle to conquer. After that, you'll need to figure out how to semantically represent the Visual Basic operations in Javascript. Depending on the original context of the code, that could be somewhat weird. (You don't mention anything about where this code all runs.)
As enriching a learning experience as this might be, it's not unlikely that translating the code by hand will (in the end) take less time and produce better results. That's particularly true if you're just now finding out that there is such a thing as a "parser".
Nice job. Sounds like you did something that might not be perfect, but it did the job.
I'd recommend looking into parsers and grammars if you want to make it more sophisticated. There are lots of parser generators that would be able to help you. You'd have to come up with a grammar for the source language, generate the lexer/parser, and then use that to generate an abstract syntax tree (AST). Once you have that, you can walk the AST and ask it to emit any code you want.
It's doable but, as Oded says, it's not trivial.

Categories

Resources