简体   繁体   中英

Get substring before and after second space in a string via JavaScript?

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)

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 );

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); 

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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM