I have a string that can look like this:
8=0,2=1,5=1,6=0,7=0
I want to extract only the numbers which are followed by =0
, in this case: 8, 6 and 7
How can I do this in JavaScript?
I have a string that can look like this:
8=0,2=1,5=1,6=0,7=0
I want to extract only the numbers which are followed by =0
, in this case: 8, 6 and 7
How can I do this in JavaScript?
Try:
'8=0,2=1,5=1,6=0,7=0'
.match(/\d?=(0{1})/g)
.join(',')
.replace(/=0/g,'')
.split(','); //=> [8,6,7] (strings)
or, if you can use advanced Array
iteration methods:
'8=0,2=1,5=1,6=0,7=0'.split(',')
.filter( function(a){ return /=0/.test(a); } )
.map( function(a){ return +(a.split('=')[0]); } ) //=> [8,6,7] (numbers)
var nums = [];
'8=0,2=1,5=1,6=0,7=0'.replace(/(\d+)=0,?/g, function (m, n) {
nums.push(+n);
});
Note that this returns an array of numbers, not strings.
Alternatively, here is a more concise, but slower, answer:
'8=0,2=1,5=1,6=0,7=0'.match(/\d+(?==0)/g);
And the same answer, but which returns numbers instead of strings:
'8=0,2=1,5=1,6=0,7=0'.match(/\d+(?==0)/g).map(parseFloat);
Try this:
function parse(s)
{
var a = s.split(",");
var b = [];
var j = 0;
for(i in a)
{
if(a[i].indexOf("=0")==-1) continue;
b[j++] = parseFloat(a[i].replace("=0",""));
}
return b;
}
Hope it helps!