0

I have this string:

[{"COUNT(post_id)":"2"}][{"COUNT(post_id)":"1"}][{"COUNT(post_id)":"2"}]

How can I take out the "2", "1", "2" and put them in an array using JavaScript?

cmbuckley
  • 40,217
  • 9
  • 77
  • 91
Grigory Volkov
  • 472
  • 6
  • 26
  • 1
    There are lots of ways, what have you tried so far? – Andy Ray Jan 06 '19 at 20:42
  • 1
    Possible duplicate of [get number only in javascript](https://stackoverflow.com/questions/17668462/get-number-only-in-javascript) – Slai Jan 06 '19 at 20:54

2 Answers2

4

Here's a few helpful resources: https://regexr.com/ https://github.com/ziishaned/learn-regex

console.log(
'[{"COUNT(post_id)":"2"}][{"COUNT(post_id)":"1"}][{"COUNT(post_id)":"2"}]'
.match(/\d+/g)
);

(This assumes each number is a single digit)

For the sake of pointing out bad code.. I wrote the following as a "fun" update to show a @Anupam's answer below. It abuses a few things... and I much prefer the regex solution.

console.log(
'[{"COUNT(post_id)":"2"}][{"COUNT(post_id)":"1"}][{"COUNT(post_id)":"2"}]'
.split('[{"COUNT(post_id)":"')
.map(function(x) { return parseInt(x); })
.filter(isFinite)
);
Layke
  • 51,422
  • 11
  • 85
  • 111
1

not a clean way but try on the lines

    var str = '[{"COUNT(post_id)":"2"}][{"COUNT(post_id)":"1"}][{"COUNT(post_id)":"2"}]';
    var res = str.split('[{"COUNT(post_id)":"');
    var res1 = res.toString();
    var res3 = res1.split('"}]');
    var res4 = res3.toString().split(',,');
    document.write(res4);
Anupam Rekha
  • 180
  • 9