简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM