通过 JavaScript 获取字符串中第二个空格之前和之后的子字符串
Get substring before and after second space in a string via JavaScript?
var str = "test test1 test2 test3";
有什么方法可以抓住"测试测试1"和"测试2测试3"吗?(第二个空格之前的任何内容和第二个空格之后的任何内容(
假设您知道字符串至少有两个空格:
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"]
相关文章:
- 正则表达式删除最后一个数字之后的字符串
- Jquery - 从查询字符串中获取“#”值之后,而不是在“?”符号值之后获取
- 如何在 javascript 中使用正则表达式提取句点 (.) 之后的字符串
- 从字符串中删除-之后的一些文本
- 使用Jquery和PHP在POST Ajax之后返回(一个空字符串)
- 从子字符串之后的字符串中获取字符串
- 我怎样才能得到这个字符串之后的所有内容
- 忽略文件扩展名jQuery之后的查询字符串
- 通过 JavaScript 获取字符串中第二个空格之前和之后的子字符串
- 删除字符串中第5个字符之后的所有字符
- 如果字符串位于iframe之后,则不会使用引导程序列表显示
- 获取javascript中/之前和之后的字符串值
- 获取每个'单词'在使用regex的Javascript字符串中的每个下划线之后
- 查找网页上字符串之后或之前出现的字符串
- 一个数组在“array.push”一些字符串之后附加了未定义.这正常吗
- javascript多行匹配在某个字符串之后
- 如何构造一个javascript正则表达式来提取特殊字符串之后的所有字符串
- 匹配出现在某个字符串之后的字符串
- 替换3个不同字符串之后的双引号之间的字符串
- NodeJs在一系列字符串之后添加字符