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?

1
  • 5
    Have you tried anything? Commented May 4, 2012 at 11:55

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

He only wants numbers not =0 part :)
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);

1 Comment

+1 but you could simplify your regex like this /(\d+)=0/g and then remove the if (keep === '0')
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!

2 Comments

Because it's enough to return the numbers. document.write will kill the site... . If you delete it, I will upvote your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.