Edmeral
Edmeral

Reputation: 185

Parse numbers from a string and push them to an array

So I have a strings like this: '5-2 7-1 8-9 7-4 1-3 1-0 2-8 8-0 6-9', it's always in this form (number, dash, number, space, number, dash, ..)

What I want to do is to transform this in to an array of integers: [5, 2, 7, 1, 8, ..., 9] I had this solution

var str = '5-2 7-1 8-9 7-4 1-3 1-0 2-8 8-0 6-9';
numbers = str.replace('-', ' ').split(' ').map(function(entry) { return parseInt(entry); }); 
// ==> [ 5, 2, 7, 8, 7, 1, 1, 2, 8, 6 ] WTF!!

So I went with this

var str = '5-2 7-1 8-9 7-4 1-3 1-0 2-8 8-0 6-9';
numbers = str.split(' ').join('').split('-').join('').split('').map(function(num) {
 return parseInt(num); 
}); // ==> [ 5, 2, 7, 1, 8, 9, 7, 4, 1, 3, 1, 0, 2, 8, 8, 0, 6, 9 ] All good!

But I don't know why the first solution doesn't work, I know the problem is with the str.replace but I can't figure out why it produce this result

Upvotes: 0

Views: 56

Answers (3)

mdlars
mdlars

Reputation: 929

Here's a jsfiddle: http://jsfiddle.net/uYKV6/10/

var str, strArr, regex;

str = '5-2 7-1 8-9 7-4 1-3 1-0 2-8 8-0 6-9';
regex = new RegExp("-", 'g');
str = str.replace(regex, " ");
strArr = str.split(" ");
console.log(strArr);

Upvotes: 0

Kevin L
Kevin L

Reputation: 1066

.replace() only replaces the first occurrence. Use a regex and do a global replace
numbers = str.replace(/-/g, ' ')....

Upvotes: 0

James Allardice
James Allardice

Reputation: 165971

The replace method only replaces the first occurrence by default. You need to use a regular expression to replace all of them:

var str = '5-2 7-1 8-9 7-4 1-3 1-0 2-8 8-0 6-9';
numbers = str.replace(/-/g, ' ').split(' ').map(function(entry) { 
//                       ^ The g flag makes the regex match all occurrences
    return parseInt(entry);
});

Upvotes: 1

Related Questions