tags:

views:

132

answers:

4

Hi all

I'm having trouble getting the following to work

if(str.endsWith('+')
{
   alert("ends in plus sign")
}

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

Thanks in advance Ruth

+2  A: 

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

if (str.substr(-1) === "+") {
  alert("ends in plus sign")
}
Mat Ryer
Negative indexes (`str.substr(-1)`) don't work on JScript (IE). To be reliable cross-browser, you need `str.substring(str.length - desiredSub.length)`.
T.J. Crowder
You can, however, use `slice`, which works with negative indexes even in IE.
bobince
A: 

Use RegExp:

    a = "csadda+"
    if (a.match(/.*\+$/)) {
        alert("Ends");
    }
Enrico Carlesso
Bit overkill, surely?
T.J. Crowder
-1 little too heavy
Fire Crow
+2  A: 

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")) {
    // ...
}
T.J. Crowder
Yea Sorry I should have wrote above, I had added an endsWith prototype. Thank you
Ruth
bobince
@bobince: Good point, although I'd have to say I can't imagine a real-world difference.
T.J. Crowder
A: 
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

kennebec
`'spoon!'.endswith('.')` - whoops. Careful making regexps from string. Also, `endswith('')` won't do what you might expect due to the overloading condition.
bobince