Javascript to java code not working [duplicate] - javascript

This question already has answers here:
Double cannot be dereferenced?
(3 answers)
Closed 7 years ago.
Hi so i am trying to convert this JavaScript code to Java i can't seem to be able to do it that good am stuck in the last part i need to convert my JavaScript code to java the encrypt part.
JavaScript Code:
Encrypt = function (strIn) {
var strOut = String();
var lenIn = strIn.length;
var i = 0;
var numRand;
while (i < lenIn) {
numRand = Math.floor(Math.random() * 66) + 36;
strOut += (strIn.charCodeAt(i) + numRand).toString(27) + numRand.toString(27);
i++;
}
return strOut;
};
Java Code:
public static String Encrypt(String strIn) {
String strOut = null;
int lenIn = strIn.length();
int i = 0;
double numRand;
while (i < lenIn) {
numRand = Math.floor(Math.random() * 66) + 36;
strOut += (strIn.charAt(i) + numRand).toString(27) + numRand.toString(27);
i++;
}
return strOut;
}
Am having an error in this line of code:
strOut += (strIn.charAt(i) + numRand).toString(27) + numRand.toString(27);
The Error:
Error:(22, 50) java: double cannot be dereferenced
I can't seem to be able to tell why any help is wonderful.
Thank you very much.

The issue you are running into that double is a primitive type (along with char and int) and so it doesn't have a toString() method (which in Java belongs to Object). To dig deeper, the reason your error message complains about a double is because your numRand variable is of type double, and so due to casting strIn.charAt(i) + numRand also becomes a double.
Instead you can use something like Integer.toString(value, radix), which is a static member of Integer. The revised code might look like...
strOut += Integer.toString((int)(strIn.charAt(i) + (char)numRand), 27) +
Integer.toString((int)numRand, 27);

Related

How to compress string by JS? [duplicate]

This question already has answers here:
Find the characters in a string which are not duplicated
(29 answers)
Closed 2 years ago.
trying writing func for compressing string(2 equal letter become 1). Don't get how to save the progress of compressing(trying different combo with concat - unsuccessful). Every time my for take full string
CodePen
let pass = '1122333456';
function CompressPass(string) {
for (let i = 0; i < string.length; i++) {
let concisePassword = string.split('');
const item = string[i];
const nextItem = string[i + 1];
console.log(+item, +nextItem);
if (item === nextItem) {
concisePassword.splice(i, 1);
console.log(concisePassword);
} else {
console.log('not equal: ', +item, +nextItem);
}
};
}
CompressPass(pass);
maybe this help you
let pass = '11223322345666600222222';
function CompressPass (string) {
string += '-';
let str = '';
for (let i = 1; i < string.length; i++) {
const nextItem = string[i];
const item = string[i - 1];
if (item != nextItem){
str += item;
}
};
return str;
}
console.log(CompressPass(pass))
you can try 'lz-string' for compressing and de-decompressing string in javascript.
** I used that for compressing local storage data ( as local storage has only a 5MB limit )
** the results may not be visible for shorter strings, but you can try it.
link: https://pieroxy.net/blog/pages/lz-string/index.html
example : (from this above-mentioned link )
<script language="javascript" src="lz-string.js"></script>
<script>
var string = "This is my compression test.";
alert("Size of sample is: " + string.length);
var compressed = LZString.compress(string);
alert("Size of compressed sample is: " + compressed.length);
string = LZString.decompress(compressed);
alert("Sample is: " + string);
</script>

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}$

convert javascript string to regular expression [duplicate]

This question already has answers here:
Match #(\w+) and replace in javascript
(2 answers)
Closed 6 years ago.
I have the following
function arrayInArray(chBox, values) {
try {
for (var y = 0; y < chBox.length; y++) {
var stringConcat = "/\b" + chBox[x] + ",?\b/";
var patt = new RegExp(eval(stringConcat));
console.log("value to check: " + chBox[y] + " " + values + " index " + patt.test(values));
but I can't get it to work. if I change it to this
var patt = new RegExp(/\b17,?\b/)
and then run
patt.test(values)
it works fine.
I'm passing in
var checkbox = ["17", "23"];
Can anyone tell me where I am going wrong
thanks
the code that works
for (var y = 0; y < chBox.length; y++) {
var stringConcat = "\\b" + chBox[y] + ",?\\b";
var patt = new RegExp(stringConcat);
if (patt.test(values) == false) return false;
}
There's no need for eval as its already a string. Just pass that to the RegExp constructor. You should also drop the leading and trailing / as that will be interpreted as part of the expression.

Adding values in javascript [duplicate]

This question already has answers here:
Plus Arithmetic Operation
(7 answers)
Closed 8 years ago.
I am trying to add up the 2 values (bold) that are inputed by the user but instead of adding then mathematically (100+1 = 101) it adds them like this (100+1 = 1001).
$('#inputcost').keyup(function(){
var price = $(this).val();
});
function checkboxcost() {
var sum = 0;
var gn, elem;
for (i=0; i<2; i++) {
gn = 'extra'+i;
elem = document.getElementById(gn);
if (elem.checked == true) { sum += Number(elem.value); }
}
**var total = (price.value + sum.toFixed(2));
document.getElementById('totalcost').value = "$" + total;**
}
</script>
<input id="totalcost" disabled/>
The problem is, as you suspect, in this line:
var total = (price.value + sum.toFixed(2));
The problem is that .toFixed converts the number to a string for display. So you are trying to add a string to a number, which results in concatenation, not addition.
You want to add the numbers together, then display the sum:
var total = (price.value + sum).toFixed(2);
With that said, I'm not sure where price.value is coming from, so it's possible that's a string too. In which case, convert it with the unary plus + operator:
var total = (+price.value + sum).toFixed(2);
Its treating price.value as String so convert that string to number like:
var total = (Number(price.value) + sum.toFixed(2));
it seems string addition is taking place.
So try converting string numbers to integer using parseInt() like:
var x = parseInt("1")
var y = parseInt("2")
var z = x + y
Try parseInt(price.value) + ...
It's because the types of the operands are strings and the + operator for two strings does concatenation, not addition.
If you convert them to numbers then you'll get a number result:
"1" + "2" == "12"
parseFloat("1") + parseFloat("2") == 3

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