เราต้องเขียนฟังก์ชันที่รับสตริง และพิมพ์ตัวเลขสำหรับแต่ละตัวอักษรตามลำดับ:
a = 1, b = 2, c = 3, ..., 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"