JS如何不使用正则,分离(切割)字母与数字

A1 输出 ['A','1']
A2 输出 ['A','2']
...
AAABBB666888 输出 ['AAABBB','666888']
要求不通过正则

阅读 5.8k
6 个回答
let letter = number = '';
'ADF221'.split('').map(item => {
    item > -1 ? number += item : letter += item
})
console.log([letter, number])

那就循环字符串,每个字符都执行一下Number(),当返回NaN的时候记一下位置,然后slice切割一下吧

let res = []
let en = ["A","B","C",..."X","Y","Z"]
let num = [1,2,3,4,5,6,7,8,9];
遍历字符串AAABBB666888
若当前遍历的元素在en数组中,则结果放到res[0]
若当前遍历的元素在num数组中,则结果放到res[1]
var a = 'AAABBB666888ssss'
var res = [], str = '', flag = isNaN(a[0])
for(let i = 0; i < a.length; i++){
    if(flag === isNaN(a[i])){
        str += a[i]
    }else{
        res.push(str)
        str = a[i]
        flag = isNaN(a[i])
    }
}
str && res.push(str)
console.log(res)
const splitStr = (str) => {
  let index = 0;
  const ans = [];
  while (index < str.length) {
    let cand = "";

    while (index < str.length && str[index] <= "9" && str[index] >= "0") {
      cand += str[index];
      ++index;
    }

    cand && ans.push(cand);
    cand = "";
    while (index < str.length && (str[index] > "9" || str[index] < "0")) {
      cand += str[index];
      ++index;
    }

    cand && ans.push(cand);
  }

  return ans;
};

console.log(splitStr('AAABBB666888adsdf')); //["AAABBB", "666888", "adsdf"]
function splitByNumber(str) {
    let isNumber = isNaN(str.charAt(0));
    let data = [], val = "";
    str.split('').forEach(v => {
        if(isNaN(v) == num) return val += v;
        data.push(val);
        val = v
        num = isNaN(v)
    })
    data.push(val);
    return data;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏