0

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

3 Answers 3

1

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

4 Comments

gah, you beat me to it
How about str.split(/[\s-]/).map(Number)?
@elclanrs - Yep, that would work but doesn't answer the question as to why the OPs attempt doesn't.
@elclanrs that's even better!
0

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

Comments

0

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

Comments

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.