Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

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


เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้สตริงอักขระ ฟังก์ชันควรสร้างสตริงใหม่ที่อักขระที่ไม่ใช่ตัวอักษรทั้งหมดจากสตริงเดิมจะถูกลบออกและส่งคืนสตริงนั้น หากสตริงมีช่องว่าง ก็ไม่ควรลบออก

ตัวอย่างเช่น −

หากสตริงอินพุตเป็น −

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

จากนั้นสตริงเอาต์พุตควรเป็น −

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

ตัวอย่าง

ต่อไปนี้เป็นรหัส -

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