我们需要编写一个函数,该函数接受一个字符串,将其修剪掉所有空格,将其转换为小写字母,并返回一个数字数组,该数字数组描述英语字母中相应字符的位置,字符串中的任何空格或特殊字符均应忽略。
例如-
Input → ‘Hello world!’ Output → [8, 5, 12, 12, 15, 23, 15, 18, 12, 4]
为此的代码将是-
const str = 'Hello world!';
const mapString = (str) => {
const mappedArray = [];
str
.trim()
.toLowerCase()
.split("")
.forEach(char => {
const ascii = char.charCodeAt();
if(ascii >= 97 && ascii <= 122){
mappedArray.push(ascii - 96);
};
});
return mappedArray;
};
console.log(mapString(str));输出结果
控制台中的输出将为-
[ 8, 5, 12, 12, 15, 23, 15, 18, 12, 4 ]