使用JavaScript按数字或字母字符将字符串拆分为大块 [英] Splitting a string into chunks by numeric or alpha character with JavaScript
问题描述
我有这个:
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 a regular expression would be best for this, but I keep getting stuck. Essentially, I tried to do a string replace, but you cannot use a regular expression 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.
有可能吗?
推荐答案
匹配字符然后加入它们可能更明智:
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按数字或字母字符将字符串拆分为大块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!