JavaScript. Assign number values to letters and perform calculations based on user's letter input

1.3k Views Asked by At

I would like to assign values to letters: A=0, B=1, C=2, D=3, E=4, F=5, G=6, H=7, I=8, J=9 and take user input from text field, for example ‘FAA’, and concatenate the number values of the user input, in the example FAA the value would be 500, then be able to take that value of, e.g., 500 (or whatever the value – if input were ECA the value would be 420) and perform a calculation with it, e.g., 2000 – (value of FAA) = 1500.

The specific application of this is an EchoSign PDF using JavaScript formulas in calculated fields that needs to take a ‘promotional code’ value input by the user, e.g., FAA, and deduct that amount from the full price field then show the new amount in the discounted price field.

2

There are 2 best solutions below

0
On

JavaScript has the feature to treat strings to some extents like arrays.

Therefore, you could, for example set up a master string.

Then you loop through your instring and read out the index of the character in the masterstring

var masterstring = "abcdefghijklmnopqrstuvwxyz" ;

var instring ; // has a value to be assigned to 
var restring = " " // the result goes into this variable

for (var i = 0 ; i < instring.length ; i++) {
  restring += masterstring.indexOf(instring.charAt(i).toLowerCase()) ;
}

This forces restring to be a string; changing it to a number would be straightforward.

0
On

Make an object with properties a, b, c etc. this will act as an map. E.g.

var map = {
  a: 0,
  b: 1, ...}

Now iterate the string your trying to make value from

var ans = 0;
for (var i = 0; i < str.length; ++i) {
  ans = ans * 10 + map[str[i]];
}

You may need to check for value bounds for ans if string is too long