0

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.

2
  • I guess you should clarify your question. 1) You are missing a bracket in the if condition, 2) String.endsWith nor String.endWith are not standard javascript functions. Commented May 7, 2010 at 16:15
  • See my comment on your accepted answer; there's an IE gotcha you'll want to be aware of. Commented May 7, 2010 at 16:31

4 Answers 4

3

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

if (str.substr(-1) === "+") {
  alert("ends in plus sign")
}
Sign up to request clarification or add additional context in comments.

2 Comments

Negative indexes (str.substr(-1)) don't work on JScript (IE). To be reliable cross-browser, you need str.substring(str.length - desiredSub.length).
You can, however, use slice, which works with negative indexes even in IE.
3

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")) {
    // ...
}

3 Comments

Yea Sorry I should have wrote above, I had added an endsWith prototype. Thank you
This version is marginally faster: var i= this.length-sub.length; return i>=0 && this.indexOf(sub, i)===i. Prototype and a few others use this approach.
@bobince: Good point, although I'd have to say I can't imagine a real-world difference.
0
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

1 Comment

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

Use RegExp:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.