开发者

JavaScript endWith()

I'm having trouble getting the following to work

if(st开发者_运维技巧r.endsWith('+')
{
   alert("ends in plus sign")
}

How do I escape the plus sign? I've tried /\ +/ but it doesn't work.


There is no endsWith method in JavaScript, so instead use:

if (str.substr(-1) === "+") {
  alert("ends in plus sign")
}


The Javascript String type doesn't have an endsWith function, but you can give it one if you like:

if (!String.prototype.endsWith) {
    (function() {
        String.prototype.endsWith = String_endsWith;
        function String_endsWith(sub) {
            return this.length >= sub.length && this.substring(this.length - sub.length) == sub;
        }
    })();
}

Or if you don't mind unnamed functions:

if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(sub) {
        return this.length >= sub.length && this.substring(this.length - sub.length) == sub;
    };
}

Either way, you could then do:

if ("foo".endsWith("oo")) {
    // ...
}


String.prototype.endswith= function(c){
    if(!c) return this.charAt(this.length - 1);
    else{
        if(typeof c== "string") c= RegExp(c + "$");
        return c.test(this);
    }
}

var s='Tell me more:', s2='Tell me about part 2:';

s.endsWith() // returns ':';

s.endsWIth(':') // returns true, last character is ':';

s2.endsWIth(/\d:?/) // returns true. string ends with a digit and a (possible) colon


Use RegExp:

    a = "csadda+"
    if (a.match(/.*\+$/)) {
        alert("Ends");
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜