Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substract 2 char in javascript to get a difference in ascii

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.

like image 273
Muthu Ganapathy Nathan Avatar asked Mar 31 '13 20:03

Muthu Ganapathy Nathan


2 Answers

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().
like image 103
David Thomas Avatar answered Sep 17 '22 03:09

David Thomas


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)

like image 24
Dave Avatar answered Sep 21 '22 03:09

Dave