endsWith in JavaScript

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

    String.prototype.endsWith = function(str) 
    {return (this.match(str+"$")==str)}
    
    String.prototype.startsWith = function(str) 
    {return (this.match("^"+str)==str)}
    

    I hope this helps

    var myStr = “  Earth is a beautiful planet  ”;
    var myStr2 = myStr.trim();  
    //==“Earth is a beautiful planet”;
    
    if (myStr2.startsWith(“Earth”)) // returns TRUE
    
    if (myStr2.endsWith(“planet”)) // returns TRUE
    
    if (myStr.startsWith(“Earth”)) 
    // returns FALSE due to the leading spaces…
    
    if (myStr.endsWith(“planet”)) 
    // returns FALSE due to trailing spaces…
    

    the traditional way

    function strStartsWith(str, prefix) {
        return str.indexOf(prefix) === 0;
    }
    
    function strEndsWith(str, suffix) {
        return str.match(suffix+"$")==suffix;
    }
    

提交回复
热议问题