我们需要编写一个包含字符串的JavaScript函数。它应该为字符串中的每个对应字母打印出每个数字。
a = 1 b = 2 c = 3 d = 4 e =5 . . . y = 25 z = 25
注意:删除任何特殊字符和空格。
因此,如果输入为-
"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"