views:

2496

answers:

4

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
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
Why shouldn't you do it? Or you just don't do it because Crockford said it?
Luca Matteis
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
+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
+3  A: 

Regular expressions

"Hello world".match(/world$/)
Chetan Sastry
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