繁体   English   中英

通过JavaScript获取字符串中第二个空格之前和之后的子字符串?

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

var str = "test test1 test2 test3";

有什么办法抢“ test test1”和“ test2 test3”? (第二个空格之前的所有内容,第二个空格之后的所有内容)

假设您知道该字符串至少有两个空格:

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

如果不确定:

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

使用split和某些数组的功能

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

正则表达式替代:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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