Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

แทนที่ตัวอักษรด้วยตำแหน่งในอักษรอังกฤษใน JavaScript

เราต้องเขียนฟังก์ชันรับสตริง ตัด whitespace แปลงเป็นพิมพ์เล็ก คืนอาร์เรย์ตัวเลขที่บอกตำแหน่งของตัวอักษรในอักษรอังกฤษ whitespace หรือตัวอักษรพิเศษในสตริงควรละเว้น

เช่น

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 ]