简体   繁体   English

解析字符串中的数字并将其推入数组

[英]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, ..) 所以我有这样一个字符串: '5-2 7-1 8-9 7-4 1-3 1-0 2-8 8-0 6-9' ,它始终是这种形式(数字,破折号,数字,空格,数字,破折号,..)

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 我想要做的就是将其转换为整数数组:[5,2,7,1,1,8,...,9]我有这个解决方案

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 但是我不知道为什么第一个解决方案不起作用,我知道问题出在str.replace但是我不知道为什么会产生这种结果

The replace method only replaces the first occurrence by default. 默认情况下, replace方法仅替换第一个匹配项。 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. .replace()仅替换第一个匹配项。 Use a regex and do a global replace 使用正则表达式并进行全局替换
numbers = str.replace(/-/g, ' ')....

Here's a jsfiddle: http://jsfiddle.net/uYKV6/10/ 这是一个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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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