JavaScript inline split(',').splice()

349 Views Asked by At

I'm trying to perform an inline split() then splice(), and it's not working.

var newValue = "61471acddbbfef00961374b5ae961943,fafd1e39db3fa20084cc74b5ae961914";
var test = (newValue.toString().split(',')).splice(0,1,'test');
console.log(test);

Output is: Array ["61471acddbbfef00961374b5ae961943"]

But I'm expecting: Array ["test","61471acddbbfef00961374b5ae961943"]

Now, if I do this:

var test = newValue.toString().split(',');
test.splice(0,1,'test');
console.log(test);

I get what I'm looking for: Array ["test","61471acddbbfef00961374b5ae961943"]

Why can't I make it all inline?: (newValue.toString().split(',')).splice(0,1,'test');

1

There are 1 best solutions below

0
tom On

If you absolutely need it as an oneliner, you can do it with concat and slice.

var str = "a,b,c";
var test = ['test'].concat(str.split(',').slice(0, 1));

console.log(test);
// output: [ "test", "a" ]