Split a string straight to into variables

You can only do it slightly more elegantly by omitting the var keyword for each variable and separating the expressions by commas:

var array = str.split('-'),
    a = array[0], b = array[1], c = array[2];

ES6 standardises destructuring assignment, which allows you to do what Firefox has supported for quite a while now:

var [a, b, c] = str.split('-');

You can check browser support using Kangax's compatibility table.


var str = '123',
    array = str.split('');

(function(a, b, c) {
    a; // 1
    b; // 2
    c; // 3
}).apply(null, array)

Split a string into two part variables for a 3 or more word sentence.

> var [firstName, lastName] = 'Ravindra Kumar Padhi'.split(/(\w+)$/)

> console.log({firstName: firstName.trim(), lastName: lastName.trim()})
{ firstName: 'Ravindra Kumar', lastName: 'Padhi' }