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 b
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;
}
which will have the desired result
'abcdefghijklmnopqrstuvwxyz'.indexOfEnd('def'); //6
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;
}
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
Note returns 23 if you have this string:
var searchString = 'abcdefghijklmnopqrstdefuvwxyz';
As a function:
function endofstring (searchStr,findStr){
return searchStr.lastIndexOf(findStr) > 0 ? searchStr.lastIndexOf(findStr) + findStr.length : -1;
}
endofstring(searchString,"def");