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?
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?
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)
);
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);