endsWith in JavaScript

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

    This is the implementation of endsWith : String.prototype.endsWith = function (str) { return this.length >= str.length && this.substr(this.length - str.length) == str; }

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

    From developer.mozilla.org String.prototype.endsWith()

    Summary

    The endsWith() method determines whether a string ends with the characters of another string, returning true or false as appropriate.

    Syntax

    str.endsWith(searchString [, position]);
    

    Parameters

    • searchString : The characters to be searched for at the end of this string.

    • position : Search within this string as if this string were only this long; defaults to this string's actual length, clamped within the range established by this string's length.

    Description

    This method lets you determine whether or not a string ends with another string.

    Examples

    var str = "To be, or not to be, that is the question.";
    
    alert( str.endsWith("question.") );  // true
    alert( str.endsWith("to be") );      // false
    alert( str.endsWith("to be", 19) );  // true
    

    Specifications

    ECMAScript Language Specification 6th Edition (ECMA-262)

    Browser compatibility

    0 讨论(0)
  • 2020-11-22 06:25
    1. Unfortunately not.
    2. if( "mystring#".substr(-1) === "#" ) {}
    0 讨论(0)
  • 2020-11-22 06:26

    Didn't see apporach with slice method. So i'm just leave it here:

    function endsWith(str, suffix) {
        return str.slice(-suffix.length) === suffix
    }
    
    0 讨论(0)
  • 2020-11-22 06:27

    if you dont want to use lasIndexOf or substr then why not just look at the string in its natural state (ie. an array)

    String.prototype.endsWith = function(suffix) {
        if (this[this.length - 1] == suffix) return true;
        return false;
    }
    

    or as a standalone function

    function strEndsWith(str,suffix) {
        if (str[str.length - 1] == suffix) return true;
        return false;
    }
    
    0 讨论(0)
  • 2020-11-22 06:28

    So many things for such a small problem, just use this Regular Expression

    var str = "mystring#";
    var regex = /^.*#$/
    
    if (regex.test(str)){
      //if it has a trailing '#'
    }

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