来自搜索字符串末尾的 JavaScript indexOf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18893402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:36:08  来源:igfitidea点击:

JavaScript indexOf from end of search string

javascript

提问by rorypicko

Javascript's String.indexOfreturns the index of the a search term within a string.

JavascriptString.indexOf返回字符串中搜索词的索引。

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

so that I can then String.substrfrom the returned value to get the string after that point.

这样我就可以String.substr从返回的值中获取该点之后的字符串。

回答by rorypicko

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!?

我用一个简单的函数对它进行了排序,但是在编写它之后,我只是认为它是如此简单和有用,以至于我无法理解为什么它尚未实现到 JavaScript 中!?

String.prototype.indexOfEnd = function(string) {
    var io = this.indexOf(string);
    return io == -1 ? -1 : io + string.length;
}

which will have the desired result

这将有想要的结果

'abcdefghijklmnopqrstuvwxyz'.indexOfEnd('def'); //6

EDIT might aswell include the lastIndexOf implementation too

编辑也可能包括 lastIndexOf 实现

String.prototype.lastIndexOfEnd = function(string) {
    var io = this.lastIndexOf(string);
    return io == -1 ? -1 : io + string.length;
}

回答by Mark Schultheiss

var findStr = "def";
var searchString = 'abcdefghijklmnopqrstuvwxyz';
var endOf = -1;
endOf = searchString.lastIndexOf(findStr) > 0 ? searchString.lastIndexOf(findStr) + findStr.length : endOf;
alert(endOf);

Alerts -1 if not found

如果未找到,警报 -1

Note returns 23 if you have this string:

如果您有此字符串,请注意返回 23:

var searchString = 'abcdefghijklmnopqrstdefuvwxyz';

As a function:

作为一个函数:

function endofstring (searchStr,findStr){
    return searchStr.lastIndexOf(findStr) > 0 ? searchStr.lastIndexOf(findStr) + findStr.length : -1;
}

endofstring(searchString,"def");