เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริง โดยควรพิมพ์ตัวเลขแต่ละตัวอักษรที่เกี่ยวข้องในสตริงออกมา
ตัวอย่างเช่น
a = 1 b = 2 c = 3 d = 4 e = 5 . . . Y = 25 Z = 26
ดังนั้นหากใส่เป็น "สวัสดีครับ"
จากนั้นผลลัพธ์ควรเป็นตัวเลขสำหรับอักขระแต่ละตัว −
"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"