将第二个空格中的字符串切成特殊字符?

时间:2016-04-21 20:17:33

标签: javascript string

var name_RawString = 'A. John Doe-John (Class of 2010)';

我尝试在第二个空格之后和(之前提取子字符串。在这种情况下:" Doe-John"。

到目前为止,我已尝试过:

var GetStr = name_RawString.slice(name_RawString.substr(0, name_RawString.indexOf(' ', name_RawString.indexOf(' ') + 1)), name_RawString.indexOf(' ('));

var StrSplit = name_RawString.split(' ');
var GetStr = name_RawString.slice(name_RawString.indexOf(StrSplit[1]) + 1)), name_RawString.indexOf(' ('));

1 个答案:

答案 0 :(得分:0)

You could give regular expressions a try:

name_RawString.match(/^(?:\S+\s){2}(.+?) \(/)[1];

Or, if You prefer a more verbose solution:

var haystack = 'A. John Doe-John (Class of 2010)';

var firstSpaceIndex = haystack.indexOf(' ');
var secondSpaceIndex = haystack.indexOf(' ', firstSpaceIndex + 1);
var openParenIndex = haystack.indexOf('(');

var needle = haystack.slice(secondSpaceIndex + 1, openParenIndex - 1);