what is the easiest way to figure out if a string ends with a certain value?
+4
A:
Stolen from prototypejs:
String.prototype.endsWith = function(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
};
'slaughter'.endsWith('laughter');
// -> true
Luca Matteis
2009-07-07 22:30:12
Some people believe that modifying the prototype of a core class is something that you shouldn't do - Crockford refers to this as "global abatement" in his book JavaScript: The Good Parts.
wrumsby
2009-07-07 22:36:31
Why shouldn't you do it? Or you just don't do it because Crockford said it?
Luca Matteis
2009-07-07 22:41:07
You shouldn't do it as it isn't guaranteed to work in all implementations of JS: the ECMAScript Compact Profile spec (ECMA-327: http://www.ecma-international.org/publications/standards/Ecma-327.htm) specifies that "Compact" implementations (e.g. on handheld devices such as phones) need not support it (see section 5.2). Even if you aren't bothered by that, it's quite possible that it will break newer versions of JS: for example, anybody who has in the past deployed code that adds a "forEach" method to Array.prototype is now breaking the native implementation in recent versions of Firefox.
NickFitz
2009-07-08 11:05:41
+12
A:
you could use Regexps, like this:
str.match(/value$/)
which would return true if the string has 'value' at the end of it ($).
cloudhead
2009-07-07 22:31:45
A:
You can always prototype String class, this will work:
String.prototype.endsWith = function(str) {return (this.match(str+"$")==str)}
You can find other related extensions for String class in http://www.tek-tips.com/faqs.cfm?fid=6620
jaime
2010-10-15 15:33:14