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

การลบตัวอักษรที่ไม่ใช่ตัวอักษรออกจากสตริงใน JavaScript

บทความนี้สาธิตฟังก์ชันลบตัวอักษรที่ไม่ใช่ตัวอักษรภาษาอังกฤษ (non-alphabetic) ออกจากสตริง โดยคงช่องว่างไว้

ตัวอย่าง

const str = 'he@656llo wor?ld';
// ผลลัพธ์: 'hello world'

ตัวอย่างโค้ด

const str = 'he@656llo wor?ld';

const isAlphaOrSpace = char => ((char.toLowerCase() !== char.toUpperCase()) || char === ' ');

const removeSpecials = (str = '') => {
  let res = '';
  const { length: len } = str;
  for (let i = 0; i < len; i++) {
    const el = str[i];
    if (isAlphaOrSpace(el)) {
      res += el;
    }
  }
  return res;
};

console.log(removeSpecials(str));

ผลลัพธ์

hello world

คำอธิบาย

ฟังก์ชัน isAlphaOrSpace ตรวจสอบว่าเป็นตัวอักษร (มีตัวพิมพ์เล็ก/ใหญ่ต่างกัน) หรือเป็นช่องว่าง

วิธีทางเลือก: ใช้ regex str.replace(/[^a-zA-Z ]/g, '')