endsWith in JavaScript

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

提交回复
热议问题