JavaScript indexOf from end of search string

前端 未结 2 1961
眼角桃花
眼角桃花 2020-12-19 03:31

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

相关标签:
2条回答
  • 2020-12-19 04:00

    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;
    }
    
    0 讨论(0)
  • 2020-12-19 04:12
    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"); 
    
    0 讨论(0)
提交回复
热议问题