endsWith in JavaScript

前端 未结 30 1003
-上瘾入骨i
-上瘾入骨i 2020-11-22 05:41

How can I check if a string ends with a particular character in JavaScript?

Example: I have a string

var str = \"mystring#\";

I wa

相关标签:
30条回答
  • 2020-11-22 06:02
    return this.lastIndexOf(str) + str.length == this.length;
    

    does not work in the case where original string length is one less than search string length and the search string is not found:

    lastIndexOf returns -1, then you add search string length and you are left with the original string's length.

    A possible fix is

    return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length
    
    0 讨论(0)
  • 2020-11-22 06:02

    For coffeescript

    String::endsWith = (suffix) ->
      -1 != @indexOf suffix, @length - suffix.length
    
    0 讨论(0)
  • 2020-11-22 06:03
    function check(str)
    {
        var lastIndex = str.lastIndexOf('/');
        return (lastIndex != -1) && (lastIndex  == (str.length - 1));
    }
    
    0 讨论(0)
  • 2020-11-22 06:04

    Its been many years for this question. Let me add an important update for the users who wants to use the most voted chakrit's answer.

    'endsWith' functions is already added to JavaScript as part of ECMAScript 6 (experimental technology)

    Refer it here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

    Hence it is highly recommended to add check for the existence of native implementation as mentioned in the answer.

    0 讨论(0)
  • 2020-11-22 06:05

    After all those long tally of answers, i found this piece of code simple and easy to understand!

    function end(str, target) {
      return str.substr(-target.length) == target;
    }
    
    0 讨论(0)
  • 2020-11-22 06:05

    Do not use regular expressions. They are slow even in fast languages. Just write a function that checks the end of a string. This library has nice examples: groundjs/util.js. Be careful adding a function to String.prototype. This code has nice examples of how to do it: groundjs/prototype.js In general, this is a nice language-level library: groundjs You can also take a look at lodash

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