Format json output by separating in commas

Asked

Viewed 191 times

3

I have an object json and I want to divide the result in commas. Example: 01,02,03,04,05

Object json:

[{"rank":"0102030405"}]

HTML output script

$.each(data, function() {
    $('div#content').append(this.rank);
});
  • Follow any pattern of size? will it always be two in two characters? what to run after rank 99?

  • The object always comes with this amount of numbers. Or Be Five Tens.

  • In my humble opinion, this has already started wrong. If possible, try to change the way these data are being sent.

  • 1

    Wouldn’t it be the case to work your back-end to return one "rank": [01, 02, ... ]? Unless you have a pattern (as mentioned by William).

  • Could work the back more want to see the solution in Js

1 answer

5


Yes, it is possible via Regex:

console.log("0102030405".match(/.{1,2}/g));

Will generate the following output:

[
  "01",
  "02",
  "03",
  "04",
  "05"
]

The parameter {1,N} specifies capture of size groups N.

You can then concatenate the results via .join():

    console.log("0102030405".match(/.{1,2}/g).join(','));

The result will be:

01,02,03,04,05

However, as commented, it would be interesting that you have this value generated in your backend if possible.

  • Bingo, @Onosendai

Browser other questions tagged

You are not signed in. Login or sign up in order to post.