7
var str = "test test1 test2 test3";

Any way to grab "test test1" and "test2 test3"? (anything before the second space and anything after second space)

2
  • 1
    Two possible approaches: regex; splitting the string at spaces and then rebuilding the components you need. Commented Mar 31, 2016 at 19:50
  • 4
    What you've tried so far? Commented Mar 31, 2016 at 19:51

3 Answers 3

7

Assuming you know the string has at least two spaces:

var str = "test test1 test2 test3";

var index = str.indexOf( ' ', str.indexOf( ' ' ) + 1 );

var firstChunk = str.substr( 0, index );
var secondChunk = str.substr( index + 1 );

If you're unsure:

var str = "test test1 test2 test3";

var index = str.indexOf( ' ', str.indexOf( ' ' ) + 1 );

var firstChunk = index >= 0 ? str.substr( 0, index ) : str.substr( index + 1 );
if ( index >= 0 )
    var secondChunk = str.substr( index + 1 );
Sign up to request clarification or add additional context in comments.

1 Comment

Hi you code works fine thanks... but if there is a leading space how to get the 1st 2 words and next 2 words? in other words how to do this for 3space? any help is appreciated :)
4

Using split and some array's functions

var str = "test test1 test2 test3";

var n = 2; // second space

var a = str.split(' ')
var first = a.slice(0, n).join(' ')
var second =  a.slice(n).join(' ');

document.write(first + '<br>');
document.write(second);

Comments

2

Regexp alternative:

var str = "test test1 test2 test3",
    parts = str.match(/^(\S+? \S+?) ([\s\S]+?)$/);

console.log(parts.slice(1,3));   // ["test test1", "test2 test3"]

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.