使用 JavaScript 从字符串中删除所有非字母字符

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/2/22 7:08:17

我们需要编写一个 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

相关文章


有用资源