0

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?

Bojangles
  • 91,543
  • 47
  • 160
  • 197

3 Answers3

4

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)
KooiInc
  • 104,388
  • 28
  • 131
  • 164
2
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);
st-boost
  • 1,767
  • 1
  • 12
  • 17
0

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!

  • Because it's enough to return the numbers. `document.write` will kill the site... . If you delete it, I will upvote your answer. –  May 04 '12 at 12:14
  • @vngeek.exe http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – Jordan May 04 '12 at 12:18