เราจำเป็นต้องเขียนฟังก์ชัน 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"