使用Javascript通过数字或alpha字符将字符串拆分为块(Splitting a string into chunks by numeric or alpha char with Javascript)

207 IT屋

So I have this:

var str = A123B234C456;

I need to split it into comma separated chunks to return something like this:

A,123,B,234,c,456

I thought regex would be best for this but i keep getting stuck, essentially I tried to do a string replace but you cannot use regex in the second argument

I would love to keep it simple and clean and do something like this but it does not work:

str = str.replace(/[\d]+/, ","+/[\d]+/);  

but in the real world that would be too simple.

Any thoughts? Thanks in advance!

解决方案

It may be more sensible to match the characters and then join them:

str = str.match(/(\d+|[^\d]+)/g).join(',');

But don't omit the quotes when you define the string:

var str = 'A123B234C456';

所以我有这个:



  var str = A123B234C456; 


我需要将其拆分为逗号分隔的块以返回如下内容:



  A,123,B,234,c,456 


我认为正则表达式最适合这个,但我一直卡住,基本上我试图做一个字符串替换,但你不能在第二个参数中使用正则表达式



我希望保持简单和干净并做这样的事情,但它不起作用:



  str = str.replace(/ [\ d] + /,","+ / [\ d] + /); 


但在现实世界中太简单了。



有什么想法?提前致谢!


解决方案

匹配角色然后加入它们可能更明智:



  str = str.match(/(\d + | [^ \d] +)/ g).join(','); 


但是在定义字符串时不要省略引号:



  var str ='A123B234C456'; 

本文地址:IT屋 » 使用Javascript通过数字或alpha字符将字符串拆分为块