How to subtract 2 char in javascript to get ascii difference

alert('g' - 'a') returns no number. ('NAN').

But I expect to get the difference between ascii as alert(103-97) => alert(6) . Therefore, 6 will be output.

In C, int i = 'g' - 'a' , will give i = 6 .

How to achieve this two-character subtraction in javascript? (easy without much effort, as shown below)

alert("g".charCodeAt(0) - "a".charCodeAt(0)) gives 6.

Appendix: I use this in a chess program.

+4
source share
3 answers

The only possible way to do what you need is what you already suggested:

 alert('g'.charCodeAt(0) - 'a'.charCodeAt(0)); 

As you know, this will lead to obtaining the ASCII character code from the 0th element of the string in each case and subtracting the second from the first.

Unfortunately, this is the only way to get the ASCII code of a given character, although using the function will be somewhat simpler, although there are not many charCodeAt() solutions given the brevity / simplicity.

Literature:

+9
source

JavaScript does not treat characters as numbers; instead, they are single-character strings. Thus, the subtraction operator will calculate 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)

+1
source

You can write yourself a custom function. Something like that:

 function asciiDif(a,b) { return a.charCodeAt(0) - b.charCodeAt(0); } 

And then:

 alert(asciiDif('g','a')); 
0
source

All Articles