Reputation: 10062
I have an array that includes 2 strings. One in a list of numbers and another is an integer. I want to get the elements from the first string from start to the place of the integer (if the integer is 2, I want the first two numbers in the string). I've written this code, but it only returns the first character in my string. Can anyone explain why? Thanks
var line = "1,2,3,4,5;2";
line = line.split(";");
console.log(line);
var reverse = line[0].slice(0, parseInt(line[1]));
console.log(reverse);
Upvotes: 2
Views: 179
Reputation: 2197
Here is code that return what you need:
var line = "1,2,3,4,5;2";
line = line.split(";");
var reverse = line[0].split(',').slice(0, parseInt(line[1])).join(',');
console.log(reverse);
Upvotes: 1
Reputation: 10219
You can use replace(',','')
to take only numbers from string.
var reverse = line[0].replace(',','').slice(0, parseInt(line[1],10));
var line = "1,2,3,4,5;2";
line = line.split(";");
console.log(line);
var reverse = line[0].replace(',','').slice(0, parseInt(line[1],10));
console.log(reverse);
Upvotes: 0
Reputation: 133453
You need to use split first element of line
array then you can use join.
var reverse = line[0].split(',').slice(0, parseInt(line[1])).join(',');
var line = "1,2,3,4,5;2";
line = line.split(";");
console.log(line);
var reverse = line[0].split(',').slice(0, parseInt(line[1])).join(',');
console.log(reverse);
Upvotes: 0