我想要做的是获取一个字符串,例如this.those.that
,并从第n个字符出现一个子字符串。因此,从字符串的开头到.
的第二次出现将返回this.those
。同样,从.
的第二次出现到字符串的结尾将返回that
。对不起,如果我的问题有雾,那就不容易解释了。另外,请不要建议制作额外的变量,结果将是字符串而不是数组。
答案 0 :(得分:75)
您可以在没有数组的情况下执行此操作,但这会占用更多代码并且可读性更低。
通常,您只想使用尽可能多的代码来完成工作,这也提高了可读性。如果您发现此任务正在成为性能问题(基准测试),然后您可以决定开始重构性能。
var str = 'this.those.that',
delimiter = '.',
start = 1,
tokens = str.split(delimiter).slice(start),
result = tokens.join(delimiter); // those.that
答案 1 :(得分:4)
试试这个:
"qwe.fs.xczv.xcv.xcv.x".replace(/([^\.]*\.){3}/, '');
"xcv.xcv.x"
"qwe.fs.xczv.xcv.xcv.x".replace(/([^\.]*\.){**nth**}/, '');
- 其中n是要删除的事件数量。
答案 2 :(得分:3)
我很困惑你为什么要纯粹使用字符串函数做事情,但我想你可以做类似以下的事情:
//str - the string
//c - the character or string to search for
//n - which occurrence
//fromStart - if true, go from beginning to the occurrence; else go from the occurrence to the end of the string
var cut = function (str, c, n, fromStart) {
var strCopy = str.slice(); //make a copy of the string
var index;
while (n > 1) {
index = strCopy.indexOf(c)
strCopy = strCopy.substring(0, index)
n--;
}
if (fromStart) {
return str.substring(0, index);
} else {
return str.substring(index+1, str.length);
}
}
但是,我强烈主张像alex这样简单的代码。
答案 3 :(得分:3)
以防有人需要"这个" && 34;那些"那些"以他在comment中描述的方式,这是一个修改过的代码:
var str = 'this.those.that',
delimiter = '.',
start = 1,
tokens = str.split(delimiter),
result = [tokens.slice(0, start), tokens.slice(start)].map(function(item) {
return item.join(delimiter);
}); // [ 'this', 'those.that' ]
document.body.innerHTML = result;

答案 4 :(得分:1)
如果你真的想坚持使用字符串方法,那么:
// Return a substring of s upto but not including
// the nth occurence of c
function getNth(s, c, n) {
var idx;
var i = 0;
var newS = '';
do {
idx = s.indexOf(c);
newS += s.substring(0, idx);
s = s.substring(idx+1);
} while (++i < n && (newS += c))
return newS;
}