在 JavaScript 中修剪和拆分字符串以形成数组

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/5 21:32:17

假设我们有一个逗号分隔的字符串,如下所示 −

const str = "a, b, c, d , e";

我们需要编写一个 JavaScript 函数,该函数接受一个这样的字符串并将其包含的所有空格删除。

然后我们的函数应该拆分字符串以形成文字数组并返回该数组。

示例

其代码为 −

const str = "a, b, c, d , e";
const shedAndSplit = (str = '') => {
   const removeSpaces = () => {
      let res = '';
      for(let i = 0; i < str.length; i++){
         const el = str[i];
         if(el === ' '){
            continue;
         };
         res += el;
      };
      return res;
   };
   const res = removeSpaces();
   return res.split(',');
};
console.log(shedAndSplit(str));

输出

控制台中的输出将是 −

[ 'a', 'b', 'c', 'd', 'e' ]

相关文章


有用资源