简体   繁体   中英

Convert letter to number in JavaScript and calculator

  var letter = document.getElementById("in_text").value;

Get value From input box

how to Convert input letter to number eg A=1 B=2 C=3 ....and how to calculate =

eg:

input: demo
output: 37(4 + 5 + 13 + 15)

This function accepts both upper and lowercase letters, and throws out everything that is not a Basic Latin Letter (AZ, az):

var letterSum = s =>
  s.toLowerCase().
  split('').
  map(s => s.charCodeAt(0)-0x60).
  filter(c => 1 <= c && c <= 26).
  reduce((x,y) => x+y, 0);

If you then try

alert(letterSum("demo"));

you will see it alert 37.

JSFiddle

You can use the built-in charCodeAt method to determine a numeric value to each character (based on its Unicode value).

For example:

var str = document.getElementById("in_text").value,
    numVal = 0,
    chars = str.split('');

for (var c in chars)
    numVal += (chars[c].toUpperCase().charCodeAt(0) - 64);

See Fiddle

function calculateStringValue(string) {
    var alphabet = "abcdefghijklmnopqrstuvwxyz";
    string = string.toLowerCase();
    var value = 0;

    for(var i = 0; i < string.length; i++) {
        value += alphabet.indexOf(string[i]) + 1;
    }

    return value;
}

Try using String.prototype.split() , index property of String.prototype.match() , String.prototype.replace() with RegExp /[^az]/ig to replace characters that are not az case insensitive, RegExp() to match input with i flag, for loop

 var a = "abcdefghijklmnopqrstuvwxyz"; var input = document.querySelector("input"); input.oninput = input.onclick = function(e) { this.value = this.value.replace(/[^az]/ig, ""); var res = 0; var n = this.value.split(""); for (var i = 0; i < n.length; i++) { res += a.match(new RegExp(n[i], "i")).index + 1 } this.nextElementSibling.innerHTML = res } input.click() 
 <form> <input type="text" id="in_text" value="demo" title="Input letters az, AZ" /> <output> </output> </form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM