在 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

更新日期:11-Dec-2020

478 次瀏覽

開始你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.