[英]Convert letter to number in JavaScript
I would like to know how to convert each alphabetic character entered to a number.我想知道如何将输入的每个字母字符转换为数字。
eg a=1, b=2 ,c=3 up to z=26例如 a=1, b=2 ,c=3 直到 z=26
In CI had managed to do something similar, by taking a character input and displaying it as an integer.在 CI 中,通过接受字符输入并将其显示为整数,设法做类似的事情。 But I'm not sure how I would do this in JavaScript.但我不确定我将如何在 JavaScript 中做到这一点。
If I get you right, the other answers are over complicated:如果我猜对了,其他答案就太复杂了:
parseInt('a', 36) - 9; // 1
parseInt('z', 36) - 9; // 26
parseInt('A', 36) - 9; // 1
parseInt('Z', 36) - 9; // 26
Now, to answer the question you asked in the comments:现在,回答您在评论中提出的问题:
function sumChars(s) { var i, n = s.length, acc = 0; for (i = 0; i < n; i++) { acc += parseInt(s[i], 36) - 9; } return acc; } console.log(sumChars("az"))
However, this notation of an integer is space consuming compared to the positional notation.但是,与位置表示法相比,这种整数表示法更占用空间。 Compare "baz" in both notations:比较两种符号中的“baz”:
sumChars("baz") // 29
parseInt("baz", 36) // 14651
As you can see, the amount of letters is the same, but the base 36 integer is way bigger.正如你所看到的,字母的数量是一样的,但以 36 为底的整数要大得多。 Moreover, converting a base 10 integer to base 36 is trivial in JavaScript:此外,将基数为 10 的整数转换为基数 36 在 JavaScript 中是微不足道的:
(14651).toString(36) // "baz"
Finally, be careful when you want to store the values.最后,当您想要存储值时要小心。 Although it sounds counterintuitive, base 2 is more compact than base 36. Indeed, one letter occupies at least 8 bits in memory:虽然听起来违反直觉,但基数 2 比基数 36 更紧凑。 事实上,一个字母在内存中至少占据 8 位:
(35).toString(2).length // 6 bits long
(35).toString(36).length * 8 // 8 bits long
Therefore I recommend to use "true" integers for storage, it's easy to get it back to base 36 anyway.因此,我建议使用“真实”整数进行存储,无论如何很容易将其恢复为基数 36。
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var letter = "h";
var letterPosition = alphabet.indexOf(letter)+1;
EDIT:编辑:
Possibility to calculate the letters inside a string, aa=2, ab=3 etc.可以计算字符串中的字母,aa=2,ab=3 等。
function str_split(string, split_length) {
// discuss at: http://phpjs.org/functions/str_split/
// original by: Martijn Wieringa
// improved by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: Onno Marsman
// revised by: Theriault
// revised by: Rafał Kukawski (http://blog.kukawski.pl/)
// input by: Bjorn Roesbeke (http://www.bjornroesbeke.be/)
// example 1: str_split('Hello Friend', 3);
// returns 1: ['Hel', 'lo ', 'Fri', 'end']
if (split_length == null) {
split_length = 1;
}
if (string == null || split_length < 1) {
return false;
}
string += '';
var chunks = [],
pos = 0,
len = string.length;
while (pos < len) {
chunks.push(string.slice(pos, pos += split_length));
}
return chunks;
}
function count(string){
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var splitted_string = str_split(string);
var count = 0;
for (i = 0; i < splitted_string.length; i++) {
var letterPosition = alphabet.indexOf(splitted_string[i])+1;
count = count + letterPosition;
}
return count;
}
console.log(count("az")); // returns 27 in the console
In JavaScript characters are not a single byte datatype, so if you want to mimick the workings of C, you need to create a mapping by yourself.在 JavaScript 中,字符不是单字节数据类型,所以如果你想模仿 C 的工作方式,你需要自己创建一个映射。
For example using a simple object as a map:例如使用一个简单的对象作为地图:
var characters: {
'a': 1,
'b': 2,
...
}
This way var number = charachters['a'];
这样var number = charachters['a'];
will set number to 1
.将 number 设置为1
。 The others have provided shorted methods, which are most likely more feasible, this one is mostly aimed for easy understanding.其他人提供了短路方法,这很可能是更可行的,这个主要是为了易于理解。
You could do it like this你可以这样做
function convertToNumbers(str){
var arr = "abcdefghijklmnopqrstuvwxyz".split("");
return str.replace(/[a-z]/ig, function(m){ return arr.indexOf(m.toLowerCase()) + 1 });
}
What your doing is creating an array of alphabets and then using the callback in String.replace
function and returning the respective indexes of the letter +1
as the indices start from 0
您所做的是创建一个字母数组,然后使用String.replace
函数中的回调并返回字母+1
的相应索引,因为索引从0
开始
This will work这将工作
"abcdefghijklmnopqrstuvwxyz".split("").forEach(function (a,b,c){ console.log(a.toLowerCase().charCodeAt(0)-96)});
"iloveyou".split("").forEach(function (a,b,c){ console.log(a.toLowerCase().charCodeAt(0)-96)});
9
12
15
22
5
25
15
21
You can make an object that maps the values-您可以制作一个映射值的对象-
function letterValue(str){
var anum={
a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10, k: 11,
l: 12, m: 13, n: 14,o: 15, p: 16, q: 17, r: 18, s: 19, t: 20,
u: 21, v: 22, w: 23, x: 24, y: 25, z: 26
}
if(str.length== 1) return anum[str] || ' ';
return str.split('').map(letterValue);
}
letterValue('zoo') returns: (Array) [26,15,15] ; letterValue('zoo')返回: (Array) [26,15,15] ;
letterValue('z') returns: (Number) 26 letterValue('z')返回:(数字)26
You can just get the ascii value and minus 64 for capital letters.您可以只获得 ascii 值和大写字母的负 64。
var letterPlacement = "A".charCodeAt(0) - 64;
Or minus 96 for lower case.或负 96 表示小写。
var letterPlacement = "a".charCodeAt(0) - 96;
Or as a nice and tidy one line function that doesn't give a damn about case:或者作为一个漂亮而整洁的单行函数,不关心案例:
function alphabetifier(letter) {
return letter.charCodeAt(0) - (letter === letter.toLowerCase() ? 96 : 64);
}
function convertAlpha(ch){ //ASCII code of a is 97 so subtracting 96 would give 1 and so on return ch.charCodeAt(0)-96; } console.log(convertAlpha("b")); // returns 2
Similar thing can be done for capital alphabets with a if clause.可以对带有 if 子句的大写字母进行类似的操作。 In case of capital alphabets we would subtract with 64 as ASCII value of 'A' is 65 so 65-64 = 1, and so on for other alphabets.在大写字母的情况下,我们将减去 64,因为 'A' 的 ASCII 值是 65,所以 65-64 = 1,对于其他字母,依此类推。
you can try this simple function.你可以试试这个简单的功能。
#Soln 1. #Soln 1。
function createIndecesFromChar() {
let hash = {};
for(let n = 1; n <= 26; n++) {
hash[String.fromCharCode(96+n)] = n; // in case of lowercase letters;
}
return hash;
}
console.log(createIndecesFromChar());
// output
// { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10, k: 11, l: 12, m: 13, n: 14, o: 15, p: 16, q: 17, r: 18, s: 19, t: 20, u: 21, v: 22, w: 23, x: 24, y: 25, z: 26 }
#Soln 2. another functional straight forward approach. #Soln 2.另一种功能直接的方法。
const indexedMap = Object.fromEntries(Array.from({ length: 26 }, (_, c) => [String.fromCharCode(97+c), c+1]));
console.log(createIndecesFromChar());
// output - same result as above.
// { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10, k: 11, l: 12, m: 13, n: 14, o: 15, p: 16, q: 17, r: 18, s: 19, t: 20, u: 21, v: 22, w: 23, x: 24, y: 25, z: 26 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.