JavaScript or jQuery string ends with utility function

后端 未结 8 1787
遥遥无期
遥遥无期 2020-12-23 23:56

what is the easiest way to figure out if a string ends with a certain value?

相关标签:
8条回答
  • 2020-12-24 00:34

    I am just expanding on what @luca-matteis has posted but to solve the issues pointed out in the comments the code should be wrapped to make sure you are not overwriting a native implementation.

    if ( !String.prototype.endsWith ) {  
        String.prototype.endsWith = function(pattern) {
            var d = this.length - pattern.length;
            return d >= 0 && this.lastIndexOf(pattern) === d;
        };
    }
    

    This is the suggested method for the Array.prototype.forEach method pointed out in the mozilla developer network

    0 讨论(0)
  • 2020-12-24 00:36

    I had no luck with the match approach, but this worked:

    If you have the string, "This is my string." and wanted to see if it ends with a period, do this:

    var myString = "This is my string.";
    var stringCheck = ".";
    var foundIt = (myString.lastIndexOf(stringCheck) === myString.length - stringCheck.length) > 0;
    alert(foundIt);
    

    You can change the variable stringCheck to be any string to check for. Better still would be to throw this in your own function like this:

    function DoesStringEndWith(myString, stringCheck)
    {
        var foundIt = (myString.lastIndexOf(stringCheck) === myString.length - stringCheck.length) > 0;
        return foundIt;
    }
    
    0 讨论(0)
  • 2020-12-24 00:37

    Regular expressions

    "Hello world".match(/world$/)
    
    0 讨论(0)
  • 2020-12-24 00:39

    ES6 supports this directly:

    'this is dog'.endsWith('dog')  //true
    
    0 讨论(0)
  • 2020-12-24 00:49

    you could use Regexps, like this:

    str.match(/value$/)
    

    which would return true if the string has 'value' at the end of it ($).

    0 讨论(0)
  • 2020-12-24 00:50

    You can always prototype String class, this will work:

    String.prototype.endsWith = function(str) {return (this.match(str+"$")==str)}

    You can find other related extensions for String class in http://www.tek-tips.com/faqs.cfm?fid=6620

    0 讨论(0)
提交回复
热议问题