3

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 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.

Is it possible?

3 Answers 3

7

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';
Sign up to request clarification or add additional context in comments.

1 Comment

Wow! Sometimes you just get caught up in over complexity. That worked perfectly!
2

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"

Comments

0

You can do it by replace() using a regular expression.

For example,

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

Now the value of str will be 'A,123,B234,C456'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.