简体   繁体   English

在第一个空格之后和特殊字符的第一个实例之前获取子字符串?

[英]Get substring after first space and before first instance of a special character?

I am successfully returning a substring before the first instance of a space in a string: 我成功返回了字符串中第一个空格实例之前的子字符串:

var str = "test1 test2 test3 (test4)";
var str_BeforeSpace = str.substr(0,str.indexOf(' '));
// returns "test1"

What I'm trying to do next is return a substring that exists after the first space and before the first instance of a "(". In this example, the desired substring is "test2 test3" (with no trailing spaces) ... 我接下来要做的是返回一个子字符串,该子字符串在第一个空格之后和“(”的第一个实例之前)存在。在此示例中,所需的子字符串为“ test2 test3”(没有尾随空格)...

Not much different: 差别不大:

str.substring(str.indexOf(' ') + 1, str.indexOf('('));

If you want to trim leading and trailing spaces, see Trim string in JavaScript? 如果要修剪开头和结尾的空格,请参见在JavaScript中修剪字符串? .

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

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