var result ="1fg";
for(i =0; i < result.length; i++){
var chr = result.charAt(i);
var hexval = chr.charCodeAt(chr)
document.write(hexval + " ");
}
This gives NaN 102 103.
Probably because it's treating the "1" as a integer or something like that. Is there a way I can convert the
"1"->string to the correct integer? In this case: 49.
So it will be
49 102 103 instead of NaN 102 103
Cheers,
Timo
The charCodeAt function takes an index, not a string.
When you pass it a string, it will try to convert the string to a number, and use 0 if it couldn't.
Your first iteration calls '1'.charCodeAt('1'). It will parse '1' as a number and try to get the second character code in the string. Since the string only has one character, that's NaN.
Your second iteration calls 'f'.charCodeAt('f'). Since 'f' cannot be parsed as a number, it will be interpreted as 0, which will give you the first character code.
You should write var hexval = result.charCodeAt(i) to get the character code at the given position in the original string.
You can also write var hexval = chr.charCodeAt(0) to get the character code of the single character in the chr string.
Related
I have a string in representation of ASCII decimal stored in a column in my db:
[104 105]
this converts to hi.
I need to be able to convert my column into string representation.
I know I can use String.fromCharCode(num,...num+1) but it doesn't quite work for me.
I would need to parse and split my db column value [104 105] into two separate vars:
var num1 = 104;
var num2 - 105;
this doesn't work when I have a complex ASCII decimal representation.
Is there a more efficient way to do this? My input would be something like [104 105 243 0 0 255...] which is in ASCII decimal and I need to get the string representation.
You need to parse that string first, by removing the [] characters, splitting at spaces, and converting the array elements to numbers.
let num_string = '[104 105]';
let nums = num_string.replace(/[\[\]]/g, '').split(' ').map(Number);
let string = String.fromCharCode(...nums);
console.log(string);
You can find the codes using match with a regex, and then map and return an array of the converted codes. Just join the array into a string at the end.
function convert(str, re) {
return str.match(/(\d+)/g).map(code => {
return String.fromCharCode(code);
}).join('');
}
console.log(convert('[104 105]'));
console.log(convert('[104 105 243 0 0 255]'));
(This is not a duplicate. I can't find the solution in the link provided).
Say I have an input from a user in an html form intended as a serial number or some such. This number can start with 0s. Example, 0001.
In Javascript, if that number (0001) is incremented, it becomes 2.
I would like to preserve the leading 0s to get 0002.
How do I do that in Javasript?
Thanks in anticipation.
Use padStart to pad the start of a number. However numbers don't start with zero so the number will have to be displayed as a string.
To find the number of zeros, you can do:
('001'.match(/^0+/) || [''])[0].length
'001'.match(/^0+/) – matches as many zeros as possible from the start of the string
|| [''] – if the match returns undefined, use an array with an empty string (aka a fallback value)
[0] – get the first value in the returned array (either the match or the fallback)
.length – get the length of the string
let nums = [
'1',
'01',
'001',
'0001'
]
let str = ''
for (let i of nums) {
let numZeros = (i.match(/^0+/) || [''])[0].length
let num = Number(i)
while (num < 20) {
str += `<p>${String(num++).padStart(numZeros + 1, '0')}</p>`
}
}
document.body.innerHTML = str
I want to write a function that will encode / decode a string to an int value. The purpose of this is so that I can encrypt text using RSA encryption / decryption methods that I wrote that are limited to only integers.
Basically what I want is something like:
encode("foo bar") // ex output: 488929774
decode(488929774) // ex output: "foo bar"
You approach has major issues, you should encode character by character, instead of trying to encode a numerical representation of the whole string
A string is a sequence of characters, using some character encoding. Characters can be represented with integers, in consequence you would be able to concatenate those integers, and generate an integer that represents the whole string. But the size of that resulting integer would be impossible to handle.
I'm going to expose what would happen if you try to convert a string into its numerical representation ( a sequence of char codes with proper padding )
If you convert each character into its UTF-16 numerical representation using str.charCodeAt(index), which can represent a value from 0 to 65535 (5 digits), you will get Numbers with different length.
Eg: 'a'.charCodeAt(0) = 97 // 2 digits
Eg: 'w'.charCodeAt(0) = 119 // 3 digits
Each character representation needs to have the same length, so has to be converted back to a String, and sometimes prefixed with some padding, using zeroes (0).
Eg : 97 = '00097' // length :5
Eg : 119 = '00119' // length :5
If you concatenate those padded charCodes, you get a long numerical string, that can be converted back to an Integer.
Eg : 'aw' = '0009700119' => Number('0009700119') = 9700119
At this point you should already been able to see the problem you will encounter : Number.MAX_SAFE_INTEGER
Demo implementation : encode() / decode()
Strings longer than 3 chars, will produce unexpected results...
function encode(myString){
let resultStr = '';
for(let i=0; i<myString.length;i++){
let str = String(myString.charCodeAt(i));
for(let a=0;a<5-str.length;a++) resultStr+=0;
resultStr+=str;
}
return Number( resultStr );
}
function decode(myInt){
let myIntStr = String(myInt);
let padding = 5- (myIntStr.length % 5);
for(let i=0; i < padding; i++){
myIntStr = '0' + myIntStr;
}
let chars = myIntStr.match(new RegExp('.{1,'+5+'}(?=(.{'+5+'})+(?!.))|.{1,'+5+'}$', 'g'))
let myStr ='';
for(let i=0; i < chars.length; i++){
myStr += String.fromCharCode( chars[i] );
}
return myStr;
}
let myString= window.prompt('insert string to encode');
let encoded = encode(myString);
console.log('Encoded:', encoded )
let decoded = decode(encoded);
console.log('Decoded:', decoded)
The longer gets the String, the bigger gets the resulting integer. And you will fast reach the maximum numeric value representable in JavaScript.
My understanding is that bellow code will create an array name digits which contains all digits from n, I'm I right?
var n = 123456789;
var digits = (""+n).split("");
But I did'n understood (""+n) ?
Can anyone help me?
Thanks in advance.
n is type of a number, with (""+n), you are basically converting n to a string, so you can use split method. numbers do not have a split method
It is doing the job of implicit type casting from int to string.
For ex.
4 + 2
returns 6
4 + 2 + "2"
returns 62
"2" + 2 + 4
returns 224
The integers following "" are implicitly converted to string and cancatenated.
var n = 123456789; create a variable n of numeric type. When you use +"" with a variable of numeric type javascript autamatically treat it as string and the operation return a string. So (""+n) will cast the n variable to string type.
When concat a number with string, js cast it to string. In your code, n is number, but when concat with a empty string(""), casting to string. In other way you can call toString() function. You can run follow snippet to try it
var n = 123456789;
console.log(typeof n); //number
console.log(typeof (""+n)); //string
console.log((""+n).split(""));
console.log(n.toString().split(""));
(""+n) means type casting the variable n into string
var n = 32; // n is integer type
n = "" + n; // now n is string type (n = "32")
var digits = n.split("");//execute string split function
//now digits = ['3','2'] (array of chars or single string charector)
I need to remove the dot in 1.400 in order to get the integer 1400, but it return 140. How do I obtain 1400 as an integer?
var var2= String(1.400) ;
var2 = var2.replace(".","");
var2=parseInt(var2);
There's no way the code you've given returns 140, since 1.400 is a number literal and gets shortened to 1.4 straight away and only then turned to string of "1.4". Therefore replacing a dot and converting to int results in 14.
It's not possible to tell JavaScript that number of 1.400 is not 1.4. You'd have to start with a string of "1.400" to get what you want.
Instead of going number -> string -> number maybe you could multiply the number by a thousand, or whatever order of magnitude is required.
Here is the problem ,
var var2= String(1.400) ;
alert(var2); //Returns 1.4 cause it is performing Number to String conversion
So , Change it to var var2= "1.400"; or var var2=number.toString();
And Update the replace to
var2.replace(/\./g,""); // : /g means all occurrence
You need to escape the . because it has the meaning of an arbitrary character in a regex.
Using this you will get your expected output.
var var2= "1.400" ;
var2 = var2.replace(".","");
var2=parseInt(var2);
Explanation:
var s1 = '2 + 2'; // creates a string primitive
var s2 = new String('2 + 2'); // creates a String object
console.log(eval(s1)); // returns the number 4
console.log(eval(s2)); // returns the string "2 + 2"
Add single-quotes around the initial string:
var var2= String('1.400');