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.
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.
There is no endsWith method in JavaScript, so instead use:
if (str.substr(-1) === "+") {
alert("ends in plus sign")
}
str.substr(-1)) don't work on JScript (IE). To be reliable cross-browser, you need str.substring(str.length - desiredSub.length).slice, which works with negative indexes even in IE.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")) {
// ...
}
var i= this.length-sub.length; return i>=0 && this.indexOf(sub, i)===i. Prototype and a few others use this approach.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
'spoon!'.endswith('.') - whoops. Careful making regexps from string. Also, endswith('') won't do what you might expect due to the overloading condition.