如何在字符串中拆分字母字符和数字字符?

时间:2016-06-22 02:44:57

标签: javascript arrays split

我有一个看起来像这样的数组:

var things = ["33bn", "2x", "Apple123"];

如何将该数组转换为:

var things = ["33", "bn", "2", "x", "Apple", "123"];

是否可以使用split和RegExp执行此操作?

我不知道该如何做到这一点,也许我可以循环遍历数组并使用RegExp拆分每个项目,然后将新数组的每个项目推入旧数组?

5 个答案:

答案 0 :(得分:8)

使用arrow-function ready browsers

things.map(t => t.match(/\d+|[A-Za-z]+/g))
    .reduce((x, y) => x.concat(y));



var things = ["33bn", "2x", "Apple123"];

var result = things.map(t => t.match(/\d+|[A-Za-z]+/g))
  .reduce((x, y) => x.concat(y));

console.log(result);




答案 1 :(得分:3)

传播算子,箭头功能:

driver = GraphDatabase.driver("bolt://localhost",
                                 auth=basic_auth('neo4j', 'password'),
                                 encrypted=True,
                                 trust=TRUST_ON_FIRST_USE)
session = driver.session()

答案 2 :(得分:0)

您可以像这样使用.reduce

var things = ["33bn", "2x", "Apple123"];

things.reduce(function(item, i){
  return item.concat(i.match(/\d+|[A-Za-z]+/g));
}, []);   

答案 3 :(得分:0)

您可以使用forEach循环并将带有展开运算符...的项目附加到新列表中。



var things = ["33bn", "2x", "Apple123"],
    other = [];
things.forEach(el=>other.push(...el.match(/\d+|[a-z]+/gi)));
console.log(other);




答案 4 :(得分:0)

这将是我的解决方案

var things = ["33bn", "2x", "Apple123"];
things = things.reduce((p,c) => p.concat(c.match(/\d+|[a-z]+/ig)),[]);
console.log(things);