endsWith in JavaScript

前端 未结 30 957
-上瘾入骨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:06

    This builds on @charkit's accepted answer allowing either an Array of strings, or string to passed in as an argument.

    if (typeof String.prototype.endsWith === 'undefined') {
        String.prototype.endsWith = function(suffix) {
            if (typeof suffix === 'String') {
                return this.indexOf(suffix, this.length - suffix.length) !== -1;
            }else if(suffix instanceof Array){
                return _.find(suffix, function(value){
                    console.log(value, (this.indexOf(value, this.length - value.length) !== -1));
                    return this.indexOf(value, this.length - value.length) !== -1;
                }, this);
            }
        };
    }
    

    This requires underscorejs - but can probably be adjusted to remove the underscore dependency.

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

    all of them are very useful examples. Adding String.prototype.endsWith = function(str) will help us to simply call the method to check if our string ends with it or not, well regexp will also do it.

    I found a better solution than mine. Thanks every one.

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

    If you're using lodash:

    _.endsWith('abc', 'c'); // true
    

    If not using lodash, you can borrow from its source.

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

    @chakrit's accepted answer is a solid way to do it yourself. If, however, you're looking for a packaged solution, I recommend taking a look at underscore.string, as @mlunoe pointed out. Using underscore.string, the code would be:

    function endsWithHash(str) {
      return _.str.endsWith(str, '#');
    }
    
    0 讨论(0)
  • 2020-11-22 06:10

    Just another quick alternative that worked like a charm for me, using regex:

    // Would be equivalent to:
    // "Hello World!".endsWith("World!")
    "Hello World!".match("World!$") != null
    
    0 讨论(0)
  • 2020-11-22 06:11
    function strEndsWith(str,suffix) {
      var reguex= new RegExp(suffix+'$');
    
      if (str.match(reguex)!=null)
          return true;
    
      return false;
    }
    
    0 讨论(0)
提交回复
热议问题