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

查看:297
本文介绍了使用Javascript通过数字或alpha字符将字符串拆分为块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个:

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';

这篇关于使用Javascript通过数字或alpha字符将字符串拆分为块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆