JavaScript or jQuery string ends with utility function

后端 未结 8 1819
遥遥无期
遥遥无期 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: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;
    }
    

提交回复
热议问题