4 ms·
In JavaScript I always use: String.prototype.startsWith = function(s) { return this.substring(0,s.length)===s; }; String.prototype.endsWith = functio
by dstein 15y ago
In JavaScript I always use:
String.prototype.startsWith = function(s) {
return this.substring(0,s.length)===s;
};
String.prototype.endsWith = function(s) {
return this.substring(this.length-s.length)===s;
};
- rudiger 15y agoWhat's the current consensus on augmentation of built-in prototypes [1]? Is it still a contentious issue? [1] http://michaux.ca/articles/javascript-the-good-parts-built-in-object-augmentation-and-namespacing http://michaux.ca/articles/javascript-the-good-parts-built-i...
- dstein 15y agoYou're okay as long as you don't extend Object which only leads to "hasOwnProperty" messiness. In cases where I might want to extend Object I use a static Object.foo(object) instead.
- kemayo 15y agoObject.prototype aside, I think it's a bad habit in any sort of large-ish system. Partially because of namespacing concerns; if prototype-extension happens in libraries you use, you might have common things like "startsWith" clobber each other with subtle incompatibilities. There's also visibility concerns. If you add random methods to things that look like language primitives it can be hard to get an overview of where they're really being used. Anecdotally, I had to go through and remove all use of prototype.js from deviantART because we decided to standardize on jQuery. It was a pain. A serious, serious pain. Because prototype.js extended Array, String, and other objects. So I had to go make a list of every single method that prototype.js added to these, and find all incidences of those somewhat-common strings in our codebase and examine them case-by-case to see if they were actually calling the prototype.js versions. By contrast, if I'd wanted to remove all use of jQuery I could have built an unambiguous list of all uses with a fairly simple grep.
- valyala 15y agoPerhaps, (this.lastIndexOf(s, 0) === 0) will work faster for startsWith(s), because it doesn't create new string just for the sole purpose of using it in a single comparison. What if s contains 1M 'a' chars, while this contains 1M 'b' chars? Your function will naturally make a copy of this, while it could only compare the first character in order to determine the result. The same applies to endWith() - { var pos = this.length - s.length; return (pos >= 0 && this.indexOf(s, pos) == pos); } will probably work faster in most cases.