alert('g' - 'a')
is returning Not a Number. ('NAN').
But I expect, to get the difference between ascii
as alert(103-97)
=> alert(6)
. Hence 6
to be output.
In C, int i = 'g' - 'a'
, will give i = 6
.
How to achieve this subtraction of 2 characters in javascript? (easily without much effort as below)
alert("g".charCodeAt(0) - "a".charCodeAt(0))
is giving 6.
Application : I am using this in chess program.
The only practicable way to do as you want is the way you've already suggested:
alert('g'.charCodeAt(0) - 'a'.charCodeAt(0));
As you know, this will retrieve the ASCII character code from 0th element of the string in each case, and subtract the second from the first.
Unfortunately this is the only way to retrieve the ASCII code of a given character, though using a function would be somewhat simpler, though given the brevity/simplicity of the charCodeAt()
solution not all that much so.
References:
String.charCodeAt()
.JavaScript doesn't treat characters as numbers; they are single-character strings instead. So the subtract operator will be calculating Number('g') - Number('a')
.
You should do 'g'.charCodeAt(0) - 'a'.charCodeAt(0)
(there is no better way, but you can wrap it in a function)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With