在 JavaScript 中重新组合字符串的字符
问题
我们需要编写一个JavaScript函数,它将字符串str作为第一个也是唯一的参数。
字符串str可以包含三种类型的字符-
英文字母:(AZ),(az)
数字: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', '! @' ]