问题描述
我想要做的是获取一个字符串,例如 this.those.that
,并从字符的第n个匹配项中获取子字符串。因此,从字符串的开头到的第二次出现。
将返回 this.those
。同样,从第二次出现。
到字符串末尾将返回那个
。对不起,如果我的问题有雾,那就不容易解释了。另外,请不要建议制作额外的变量,结果将是字符串而不是数组。
What I want to do is take a string such as this.those.that
and get a substring to or from the nth occurrence of a character. So, from the start of the string to the 2nd occurrence of .
would return this.those
. Likewise, from the 2nd occurrence of .
to the end of the string would return that
. Sorry if my question is foggy, it's not that easy to explain. Also, please do not suggest making extra variables, and the result will be in a string and not an array.
推荐答案
你可以没有数组就可以做到,但是需要更多的代码并且可读性更低。
You could do it without arrays, but it would take more code and be less readable.
通常,您只想使用尽可能多的代码来完成工作,这也提高了可读性。如果您发现此任务正在成为性能问题(基准测试),然后您可以决定开始重构性能。
Generally, you only want to use as much code to get the job done, and this also increases readability. If you find this task is becoming a performance issue (benchmark it), then you can decide to start refactoring for performance.
var str = 'this.those.that',
delimiter = '.',
start = 1,
tokens = str.split(delimiter).slice(start),
result = tokens.join(delimiter); // those.that
。
这篇关于在第n次出现的字符处剪切一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!