Jeremy John
Jeremy John

Reputation: 1715

Split string for first two white spaces

I have this string

var str = "394987011016097814 1d the quick brown fox jumped over the lazy dog";

..and i'm trying to get it to become this array

[
    "394987011016097814",
    "1d",
    "the quick brown fox jumped over the lazy fox",
]

I've seen this answer Split string on the first white space occurrence but that's only for first space.

Upvotes: 2

Views: 999

Answers (6)

North Halcyon
North Halcyon

Reputation: 127

use regex ^(\d+)\s(\S+)\s(.*) this way

var re = new RegExp(/^(\d+)\s(\S+)\s(.*)/, 'gi');
re.exec('394987011016097814 1d the quick brown fox jumped over the lazy fox');

var re = new RegExp(/^(\d+)\s(\S+)\s(.*)/, 'g');
var [, g1, g2, g3] = re.exec('394987011016097814 1d the quick brown fox jumped over the lazy fox');
console.log([g1, g2, g3]);

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

You can split first on all the space and than take the two values and join the remaining values.

var str = "394987011016097814 1d the quick brown fox jumped over the lazy fox";
let op = str.split(/[ ]+/g)

let final = [...op.splice(0,2), op.join(' ')]

console.log(final)

Upvotes: 1

Sanasol
Sanasol

Reputation: 912

Source: Split a string only the at the first n occurrences of a delimiter

var string = 'Split this, but not this',
    arr = string.split(' '),
    result = arr.splice(0,2);

result.push(arr.join(' ')); // result is ["Split", "this,", "but not this"]

alert(result);

Upvotes: 3

ellipsis
ellipsis

Reputation: 12152

Destructure using split and join

var str = "394987011016097814 1d the quick brown fox jumped over the lazy fox";
var [str1, str2, ...str3] = str.split(' ');
str3 = str3.join(' ');
console.log([str1, str2, str3])

Upvotes: 5

Nafis Islam
Nafis Islam

Reputation: 1509

let str = "394987011016097814 1d the quick brown fox jumped over the lazy fox";
let arr = [];             
str = str.split(' ');     
arr.push(str.shift());    
arr.push(str.shift());    
arr.push(str.join(' '));
console.log(arr);

Upvotes: 0

Dave
Dave

Reputation: 2190

You can achieve this by writing some code:

const str = "394987011016097814 1d the quick brown fox jumped over the lazy fox";

const splittedString = str.split(' ');
let resultArray = [];
let concatenedString = '';

for (let i = 0; i < splittedString.length; i++) {
    const element = splittedString[i];
    if (i === 0 || i === 1) {
        resultArray.push(element);
    } else {
        concatenedString += element + ' ';
    }
}

resultArray.push(concatenedString.substring(0, concatenedString.length - 1));

console.log(resultArray);

// output is: 
// [ '394987011016097814',
// '1d',
// 'the quick brown fox jumped over the lazy fox' ]

Upvotes: 0

Related Questions