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
so that I can then String.substr
from the returned value to get the string after that point.
The indexOf() and lastIndexOf() function return a numeric index that indicates the starting position of a given substring in the specified metadata string: indexOf() returns the index for the first occurrence of the substring. lastIndexOf() returns the index for the last occurrence of the substring.
Definition and Usage The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found.
The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.
lastIndexOf() The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex .
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");
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With