11

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.

Teemu
  • 22,918
  • 7
  • 53
  • 106
rorypicko
  • 4,194
  • 3
  • 26
  • 43

2 Answers2

17

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;
}
rorypicko
  • 4,194
  • 3
  • 26
  • 43
1
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"); 
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100