在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP