JavaScript indexOf来自搜索字符串的结尾 [英] JavaScript indexOf from end of search string
问题描述
Javascript的 String.indexOf
返回字符串中搜索词的索引。
Javascript's String.indexOf
returns the index of the a search term within a string.
它返回从搜索字符串的开头开始首次找到字符串的索引。例如:
It returns the index of where the string is first found, from the beginning of the search string. example:
'abcdefghijklmnopqrstuvwxyz'.indexOf('def') = 3;
但我需要在搜索结束时获取它,例如:
But I need to get it from the end of the search, for example:
'abcdefghijklmnopqrstuvwxyz'.indexOf('def') = 6; //essentially index + searchString.length
这样我就可以 String。 substr
从返回的值中获取该点之后的字符串。
so that I can then String.substr
from the returned value to get the string after that point.
推荐答案
我将其排序为简单的功能,但在写完之后,我只是觉得它很简单,很有用,我无法理解为什么它还没有被实现为JavaScript!?
I sorted this with a simple function, but after writing it, I just thought it was that simple, and useful that i couldnt understand why it wasn't already implemented into JavaScript!?
String.prototype.indexOfEnd = function(string) {
var io = this.indexOf(string);
return io == -1 ? -1 : io + string.length;
}
将获得所需的结果
'abcdefghijklmnopqrstuvwxyz'.indexOfEnd('def'); //6
EDIT也可能包含lastIndexOf实现
EDIT might aswell include the lastIndexOf implementation too
String.prototype.lastIndexOfEnd = function(string) {
var io = this.lastIndexOf(string);
return io == -1 ? -1 : io + string.length;
}
这篇关于JavaScript indexOf来自搜索字符串的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!