最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论
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)

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)

Share Improve this question asked Mar 31, 2016 at 19:48 faalbanefaalbane 1051 gold badge1 silver badge5 bronze badges 2
  • 1 Two possible approaches: regex; splitting the string at spaces and then rebuilding the components you need. – Andre M Commented Mar 31, 2016 at 19:50
  • 4 What you've tried so far? – Victor Commented Mar 31, 2016 at 19:51
Add a comment  | 

3 Answers 3

Reset to default 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 );

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"]
发布评论

评论列表(0)

  1. 暂无评论