Javascript String.indexOf返回字符串中搜索词的索引.
它从搜索字符串的开头返回首次找到字符串的索引.例:
'abcdefghijklmnopqrstuvwxyz'.indexOf('def') = 3;
Run Code Online (Sandbox Code Playgroud)
但我需要从搜索结束时获取它,例如:
'abcdefghijklmnopqrstuvwxyz'.indexOf('def') = 6; //essentially index + searchString.length
Run Code Online (Sandbox Code Playgroud)
这样我就可以String.substr从返回的值中获取该点之后的字符串.
我整理这个用一个简单的功能,但写它后,我只是认为这是简单,实用是我不能明白为什么它是不是已经落实到JavaScript!?
String.prototype.indexOfEnd = function(string) {
var io = this.indexOf(string);
return io == -1 ? -1 : io + string.length;
}
Run Code Online (Sandbox Code Playgroud)
这将产生预期的结果
'abcdefghijklmnopqrstuvwxyz'.indexOfEnd('def'); //6
Run Code Online (Sandbox Code Playgroud)
编辑也可能包括lastIndexOf实现
String.prototype.lastIndexOfEnd = function(string) {
var io = this.lastIndexOf(string);
return io == -1 ? -1 : io + string.length;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9955 次 |
| 最近记录: |