我们需要编写一个包含字符串的JavaScript函数。它应该为字符串中的每个对应字母打印出每个数字。
例如,
a = 1 b = 2 c = 3 d = 4 e = 5 . . . Y = 25 Z = 26
因此,如果输入的是“ hello man”,
然后输出应该是每个字符的数字-
"8,5,12,12,15,13,1,14"
以下是代码-
const str = 'hello man';
const charPosition = str => {
str = str.split('');
const arr = [];
const alpha = /^[A-Za-z]+$/;
for(i=0; i < str.length; i++){
if(str[i].match(alpha)){
const num = str[i].charCodeAt(0) - 96;
arr.push(num);
}else{
continue;
};
};
return arr.toString();
}
console.log(charPosition(str));输出结果
这将在控制台中产生以下输出-
"8,5,12,12,15,13,1,14"