Splitting a string into chunks by numeric or alpha char with Javascript

回眸只為那壹抹淺笑 提交于 2019-11-26 18:35:46

问题


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!


回答1:


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



回答2:


Hi You can do it by replace using regex for example

var str = "A123B234C456";
str = str.replace(/([a-bA-B])/g, '$1,');

now str value will be 'A,123,B234,C456';




回答3:


String split method can be called with a regexp. If the regexp has a capture group, the separator will be kept in the resulting array. So here you go :

let c = "A123B234C456";
let stringsAndNumbers = c.split(/(\d+)/); // ["A","123","B","234","C","456",""]

Since your example ends with numbers, the last element will be empty. Remove empty array elements :

let stringsAndNumbers = c.split(/(\d+)/).filter(el => el != ""); // ["A","123","B","234","C","456"]

Then join :

let stringsAndNumbers = c.split(/(\d+)/).filter(el => el != "").join(","); // "A,123,B,234,C,456"


来源:https://stackoverflow.com/questions/6060352/splitting-a-string-into-chunks-by-numeric-or-alpha-char-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!