How to get ASCII of number in JavaScript? - javascript

I am aware of name.charCodeAt(0). I am having issued with the following code, so I want a solution for below.
var number= 2;
var t = number.charCodeAt(0);
console.log(t);
The answer needs to be in ASCII. I am getting the log as 2 and not as ASCII value 50. What can be the issue?

ASCII is a way of representing String data. You need to first convert your Number to String;
Remember also that String can have arbitrary length so you'll need to iterate over every character.
var x = 2,
str_x = '' + x,
chrs = Array.prototype.map.call(str_x, function (e) {return e.charCodeAt(0);});
chrs; // [50]
Finally, JavaScript works with UTF-16/UCS-2 and not plain ASCII. Luckily the values for digits are the same in both so you don't have to do any further transformation here.

You have to cast a number to a string first to use .charCodeAt to get the numerical character code.
var number = 2;
var t = String( number ).charCodeAt( 0 );
console.log( t ); // 50

Just convert the number to String and call the method on it.
var number = 2;
var numberInString = number.toString();
var code = numberInString.charCodeAt(0);
console.log(code);

Related

How to get the number before percentage symbol in a string?

These are some possible strings. The number percentage is always at beginning.
var string = "0.5% - corresponding something" or var string = "23% - correspondig something";
I need to get the the entire number before the percentage symbol.
I already tried some solutions in cutting the string, but the problem is that the number doesn't have always the same length.
Can you help me?
There are several solutions. For example:
let antani = "23% - correspondig something";
// using parseFloat
console.log(parseFloat(antani));
// using split
console.log(antani.split("%")[0]);
first split string using '%'
<script>
var str = "0.5% - corresponding something";
var res = str.split("%");
number=res[0];
console.log(res[0]);
</script>
Using Regular expression you can match the numbers (including dots) before the percentage sign.
Example:
var text = "0.5% - corresponding something";
var percentageRegex = /([0-9\.]+).+/;
var matches = percentageRegex.exec(text);
console.log(matches[1]);

Javascript: How cut out part of an integer?

How to cut out part of an integer?
What can i do to get an integer 12 or 123 from a variable n
let n = 123456;
A simple way to do this would be to just cast the input number to a string, and then take a substring:
var n = 123456;
n = n + "";
var output = n.slice(0, 2);
console.log(output);
Another approach, if all you want is to get some number of leading digits, would be to divide by the correct multiple of ten, e.g.
var n = 123456;
var output = Math.floor(output / 10000);
The strategy I suggest is to convert the integer value to a string which you may manipulate with parseInt() as well as the string's substr() method, as follows:
const START = 0;
const first_two = 2;
const first_three = 3;
const base_ten = 10;
let n = 123456;
let res = parseInt( String( n ).substr( START,first_two ),base_ten );
console.log(res);
res = parseInt(String( n ).substr( START,first_three ),base_ten );
console.log(res);
The Number Object has a toString() method but apparently it is safer to convert the integer to a string by passing the integer value of n to the String Object per this discussion. You may then use the String Object's substr() method to access the first two or three digits appearing in the string. Next, you may take the resulting numeric string and pass it to parseInt(), along with a base parameter to obtain the integer value.
I think this will work for you - you first change it to string and split it to an array and then remove the unwanted characters, then join the array together, and parse it as an integer: (edited to reflect #VLAZ's comment.
parseInt(n.toString().slice(0,2)));

Trim long number in JavaScript

For example, I got that long nubmer 1517778188788. How can i get first 6 digits from that number, like 151777 and trim another digits?
Just convert a number to string and then slice it and convert it back to Number.
const a = 1517778188788;
const str_a = a.toString();
const result = Number(str_a.slice(0, 6));
new String(your_number).substring(0,6)
(basically converting it to a string and substringing it). Don't forget to parse it back afterwards
Applicable only when you want to strip last 7 digits, and the numbers have constant length (13 in this case). Still leaving you with first 6 ones though.
const nr = 1517778188788;
const result = Math.floor(nr / 10000000)
Try this:
var num = 1517778188788; // long number
var str = num.toString(); //convert number to string
var result = str.substring(0,6) // cut six first character
result = parseInt(result); // convert it to a number
here is a working fiddle

Javascript getting number from string

I have a string:
var example = 'sorted-by-' + number;
Where number variable can be any positive integer. I don't know how to reverse this process, not knowing how many digits this number has. I want to get from example string a number at the end.
var outputNumber = example.substring(10);
This is the simple solution because example string always start with 'sorted-by-'.
let num = + string.substr(10);
You can use String#replace function to replace sorted-by- to empty string and after that convert left part to a number:
var example = 'sorted-by-' + 125;
var num = +example.replace('sorted-by-', '');
console.log(num);
You can split string at - and get last element using pop().
var example = 'sorted-by-' + 100.99
var n = +(example.split('-').pop())
console.log(n)
You can also use regex for this.
var number = 245246245;
var example = 'sorted-by-' + number;
var res = example.match(/^sorted-by-(\d+)/);
console.log(+res[1]);

RegEx for filling up string

I have the following input:
123456_r.xyz
12345_32423_131.xyz
1235.xyz
237213_21_mmm.xyz
And now I need to fill up the first connected numbers to 8 numbers leading with 0:
00123456_r.xyz
00012345_32423_131.xyz
00001235.xyz
00237213_21_mmm.xyz
My try was to split a the dot, then split (if existing) at the underscore and get the first numbers and fill them up.
But I think there will be a more efficient way with the regex replace function with just the one function, right? How would this look like?
TIA
Matt
I would use a regex, but just for the spliting :
var input = "12345_32423_131.xyz";
var output = "00000000".slice(input.split(/_|\./)[0].length)+input;
Result : "00012345_32423_131.xyz"
EDIT :
the fast, no-splitting but no-regex, solution I gave in comments :
"00000000".slice(Math.min(input.indexOf('_'), input.indexOf('.'))+1)+input
I wouldn't split at all, just replace:
"123456_r.xyz\n12345_32423_131.xyz\n1235.xyz\n237213_21_mmm.xyz".replace(/^[0-9]+/mg, function(a) {return '00000000'.slice(0, 8-a.length)+a})
There's a simple regexp to find the part of the string you want to replace, but you'll need to use a replace function to perform the action you want.
// The array with your strings
var strings = [
'123456_r.xyz',
'12345_32423_131.xyz',
'1235.xyz',
'237213_21_mmm.xyz'
];
// A function that takes a string and a desired length
function addLeadingZeros(string, desiredLength){
// ...and, while the length of the string is less than desired..
while(string.length < desiredLength){
// ...replaces is it with '0' plus itself
string = '0' + string;
}
// And returns that string
return string;
}
// So for each items in 'strings'...
for(var i = 0; i < strings.length; ++i){
// ...replace any instance of the regex (1 or more (+) integers (\d) at the start (^))...
strings[i] = strings[i].replace(/^\d+/, function replace(capturedIntegers){
// ...with the function defined above, specifying 8 as our desired length.
return addLeadingZeros(capturedIntegers, 8);
});
};
// Output to screen!
document.write(JSON.toString(strings));

Categories

Resources