使用 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屋!