Splitting a string into chunks by numeric or alpha character with JavaScript

前端 未结 3 1323
天涯浪人
天涯浪人 2020-12-04 02:57

I have this:

var str = A123B234C456;

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

A,123,B,234         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 03:28

    The string split method can be called with a regular expression.

    If the regular expression 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"
    

提交回复
热议问题