在 JavaScript 中重新组合字符串的字符

PHPz
PHPz 转载
2023-09-16 21:41:02 630浏览

在 JavaScript 中重新组合字符串的字符

问题

我们需要编写一个 JavaScript 函数,它将字符串 str 作为第一个也是唯一的参数。

字符串 str 可以包含三种类型字符数 -

  • 英文字母:(A-Z)、(a-z)

  • 数字:0-9

  • 特殊字符 - 所有其他剩余字符

我们的函数应该迭代该字符串并构造一个包含以下内容的数组:正好三个元素,第一个包含字符串中存在的所有字母,第二个包含数字,第三个特殊字符保持字符的相对顺序。我们最终应该返回这个数组。

例如,如果函数的输入是

输入

const str = 'thi!1s is S@me23';

输出

const output = [ 'thisisSme', '123', '! @' ];

示例

以下是代码 -

实时演示

const str = 'thi!1s is S@me23';
const regroupString = (str = '') => {
   const res = ['', '', ''];
   const alpha = 'abcdefghijklmnopqrstuvwxyz';
   const numerals = '0123456789';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(alpha.includes(el) || alpha.includes(el.toLowerCase())){
         res[0] += el;
         continue;
      };
      if(numerals.includes(el)){
         res[1] += el;
         continue;
      };
      res[2] += el;
   };
   return res;
};
console.log(regroupString(str));

输出

[ 'thisisSme', '123', '! @' ]

以上就是在 JavaScript 中重新组合字符串的字符的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除