เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงที่อาจมีอักขระพิเศษบางตัว ฟังก์ชันควรส่งคืนสตริงใหม่ควรมีอักขระพิเศษทั้งหมดแทนที่ด้วยค่า ASCII ที่สอดคล้องกัน
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const str = 'Th!s !s @ str!ng th@t cont@!ns some special characters!!';
const specialToASCII = str => {
let res = '';
for(let i = 0; i < str.length; i++){
if(+str[i] || str[i].toLowerCase() !== str[i].toUpperCase() || str[i] === ' '){
res += str[i];
continue;
};
res += str[i].charCodeAt(0);
};
return res;
};
console.log(specialToASCII(str)); ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ในคอนโซล -
Th33s 33s 64 str33ng th64t cont6433ns some special characters3333