tags:

views:

844

answers:

19

What are your most useful, most practical methods that extends built-in JavaScript objects like String, Array, Date, Boolean, Math, etc.?

String

Array

Date

Note : Please post one extended method per answer.

A: 

Use the prototype chain like this:

String.prototype.AddWorld = function() { return this+'World' }

"Hello ".AddWorld(); // returns the string "Hello World"
Soubok
-1 as it is not useful or practical.
SolutionYogi
hahaha, +1 for creativity
Anurag
+2  A: 

String Padding :

String.prototype.padLeft = function (length, character) { 
     return new Array(length - this.length + 1).join(character || ' ') + this; 
}
'trial'.padLeft(7, 'X'); // output : 'XXtrial'
'trial'.padLeft(7);      // output : '  trial'



String.prototype.padRight = function (length, character) { 
     return this + new Array(length - this.length + 1).join(character || ' '); 
}
'trial'.padRight(7, 'X'); // output : 'trialXX'
'trial'.padRight(7);      // output : 'trial  '
Canavar
+11  A: 
Array.prototype.indexOf = Array.prototype.indexOf || function (item) {
    for (var i=0; i < this.length; i++) {
        if(this[i] === item) return i;
    }
    return -1;
};

Usage:

var list = ["my", "array", "contents"];
alert(list.indexOf("contents"));     // outputs 2
Makram Saleh
This method is implemented in most browsers so you could add an existence check before overwriting something that can be already done. IMO you should wrap this code inside if (Array.prototype.indexOf === undefined) {...}
RaYell
RaYell, updated the code not to redefine indexOf if it's already present.
SolutionYogi
+1  A: 

String Replace All :

String.prototype.replaceAll = function(search, replace)
{
    //if replace is null, return original string otherwise it will
    //replace search string with 'undefined'.
    if(!replace) 
        return this;

    return this.replace(new RegExp('[' + search + ']', 'g'), replace);
}

var str = 'ABCADRAE';
alert(str.replaceAll('A','X')); // output : XBCXDRXE
Canavar
This is a nice enhancement but to make it even better you could add two parameters to the function definition and use them instead of arguments array. This will shorten the code to two lines. Personally I don't see any point of using arguments array if your function doesn't need to accept arbitrary number of arguments.
RaYell
RaYell, what you said makes sense. Will edit the post.
SolutionYogi
Another improvement: if you add any regexp special characters you might get unexpected results. i.e. if you pass '.' as a search string you will replace all the characters. To avoid that change your regex to something like new RegExp('[' + search ']')
RaYell
That's a great catch buddy. You should start editing these posts! :)
SolutionYogi
@RaYell - that won't work if you want to replace more than one character at a time, e.g. `'foobar'.replaceAll('foo')`. I think it's better to make it clear that a regexp is accepted as the first argument.
harto
(actually it will work for my example, but hopefully my point makes sense :)
harto
Awesome, thanks, I like this one..
Canavar
Indeed that may not work correctly if you replace words with that. Then perhaps a better solution would if be to check what type the search parameter is. If it's a string you could then just escape all special characters, if it's a regex (typeof is object) then you could just use it as it is.
RaYell
Another small fix: if replace is undefined you should return this.toString();, because this contains String object not an actual string.
RaYell
I posted below another implementation of replaceAll method that correctly handles both string and regular expressions, it uses split and join methods instead of creating regular expressions and doing replaces with them.
RaYell
+1  A: 

Date.toMidnight

Date.prototype.toMidnight = function(){ 
  this.setMinutes(0); 
  this.setSeconds(0); 
  this.setHours(0) 
}
seth
Poorly named, since it modifies the date object, instead of returning a different value like other toX methods.
Miles
+4  A: 
// left trim
String.prototype.ltrim = function () {
    return this.replace(/^\s+/, '');
}

// right trim
String.prototype.rtrim = function () {
    return this.replace(/\s+$/, '');
}

// left and right trim
String.prototype.trim = function () {
    return this.ltrim().rtrim();
}
RaYell
+4  A: 

There are a ton of String.prototype functions from James Padolsey

http://github.com/jamespadolsey/string/tree/master

These include:

  • camelize
  • contains
  • count
  • enclose
  • extract
  • forEach
  • forEachWord
  • linkify
  • many
  • randomize
  • remove
  • reverse
  • shorten
  • sort
  • toDOM
  • trim
  • wrap
Jon Erickson
+6  A: 

String.format

String.prototype.format = function(values)
{
    var regex = /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g;

    var getValue = function(key)
                   {
                        if(values == null || typeof values === 'undefined')
                            return null;

                        var value = values[key];
                        var type = typeof value;

                        return type === 'string' || type === 'number' ? value : null;
                   };

    return this.replace(regex, function(match) 
                                { 
                                    //match will look like {sample-match}
                                    //key will be 'sample-match';
                                    var key = match.substr(1, match.length - 2);

                                    var value = getValue(key);

                                    return value != null ? value : match;
                                });
};

Usage:

alert('Program: {key1} {key2}'.format({ 'key1' : 'Hello', 'key2' : 'World' })); //alerts Program: hello world
SolutionYogi
thats a good one. Would be really cool if it was extended to mimick the C# one where you can specify a context sensitive formatting for dates/numbers/objects eg. String.Format("{0:d}", val)
Darko Z
I think Microsoft's ASP.NET Ajax library has string.Format which mimics C#'s string.Format method.
SolutionYogi
You are right Nosredna, fixed the post.
SolutionYogi
+1  A: 

Array contains:

Array.prototype.contains = function(obj) {
    for (var i=0; i < this.length; i++) {
        if(this[i] === obj) return i;
    }
    return -1;
}

Usage:

var arr = [1, 2, 3];
alert(arr.contains(2));

This little helper function tells you if your array contains an object. If it does then the index of the object is returned, otherwise -1 is returned.

Free Friday afternoon tip: don't ever ever ever modify the Object prototype. That would be just asking for a whole world of pain - I learnt this the hard way :)

Darko Z
That's the same as Array.indexOf() method posted above. I would suggest going for indexOf since it's already implemented in most browsers.
RaYell
I think it's fine to modify the object prototype in some circumstances - so long as you aren't developing Yet Another JavaScript Library, that is. It just means you have to be careful when iterating over object members (i.e. use hasOwnProperty) - but of course, you could add a method to the object prototype that handles the iteration for you :)
harto
+2  A: 

The various list manipulation prototypes are always great. Since you want only one per post, I'll just post foldl, which I discovered via SML (it "folds" the list, left to right, it has a counter part in foldr of course).

Array.prototype.foldl = function(fnc,start) {
    var a = start;
    for (var i = 0; i < this.length; i++) {
        a = fnc(this[i],a);
    }
    return a;
}

Some trivial examples could be:

var l = ["hello" , "world"];
l.foldl(function(i, acc) { return acc+" "+i; }, "") // => returns "hello world"

Sadly, the failure of standard DOM methods to return true arrays makes alot of these such methods rather useless. And if you're using a Lib of some sort, they often define methods like these already (map, filter, exists, etc).

Svend
+1  A: 

Here's the nice extension for the Date object that allows you to format the date very easily. It uses PHP's date syntax so those familiar with PHP will get it in no time. Others have a huge list of possible switches on the site as well. Personally I haven't found easier way to format dates to various formats.

Date Format

RaYell
+2  A: 

Here's another implementation of String.replaceAll() method

String.prototype.replaceAll = function(search, replace) {
    if (replace === undefined) {
        return this.toString();
    }
    return this.split(search).join(replace);
}

The difference between this one and solution posted here is that this implementation handles correctly regexp special characters in strings as well as allows for word matching

RaYell
Why would you need to do .toString? If replace is undefined, you are assigning original object back to itself.e.g. string test = "hello"; test = test.replace("hello");
SolutionYogi
RaYell
+1  A: 

PHP.JS is a very nice effort to port most of PHP's functions to JavaScript. They currently have an extremely impressive list:

Online at: http://phpjs.org/functions/index

Jonathan Sampson
+1  A: 

A collection of functions I use a lot can be found here:

http://svn.asplib.org/asplib1.2/core/string.asp

http://docs.hyperweb.no/objects/String/

thomask
+1  A: 

I have used the Array.Map function outlined by Scott Koon a couple of times.

http://www.lazycoder.com/weblog/2009/08/12/a-simple-map-function-for-plain-javascript-arrays/

Array.prototype.map = function(fn) {
    var r = [];
    var l = this.length;
    for(i=0;i<l;i++)
    {
        r.push(fn(this[i]));
    }
    return r; 
};
JamesEggers
A: 
// This replaces all instances of 'from' to 'to' even when
// 'from' and 'to' are similar (i.e .replaceAll('a', 'a '))
String.prototype.replaceAll = function(from, to) {
    var k = this;
    var i = 0;
    var j = from.length;
    var l = to.length;

    while (i <= k.length)
        if (k.substring(i, i + j) == from) {
        k = k.substring(0, i) + k.substring(i).replace(from, to);
        i += l;
    }
    else
        i++;

    return k;
};
Theofanis Pantelides
It is easier to use the 'g' (global match) flag and do a regular replace. `"abaababa".replace(/a/g, "c") => "cbccbcbc"`
Chetan Sastry
+2  A: 

Function.prototype.bind from the Prototype library.

Similar to call and apply but allows you to return a reference to a function that is called in a particular context instead of executing it immediately. Also allows you to curry parameters. It's so useful that it became a part of ECMAScript 5 and is already being implemented natively in browsers.

Function.prototype.bind = function() {
  var __method = this, args = Array.prototype.slice.call(arguments), object = args.shift();
  return function() {
    var local_args = args.concat(Array.prototype.slice.call(arguments));
    if (this !== window) local_args.push(this);
    return __method.apply(object, local_args);
  }
}
Jimmy Cuadra
+1  A: 

These two are wrappers for inserting and deleting elements from a particular position in an Array because I don't like the name splice.

// insert element at index
Array.prototype.insertAt = function(element, index) {
    this.splice(index, 0, element);
}

// delete element from index
Array.prototype.removeAt = function(index) {
    this.splice(index, 1);
}

Some more useful Array methods to get away from using indexes:

Array.prototype.first = function() {
    return this[0] || undefined;
};

Array.prototype.last = function() {
    if(this.length > 0) {
        return this[this.length - 1];
    }
    return undefined;
};

Array.prototype.max = function(array){
    return Math.max.apply(Math, array);
};

Array.prototype.min = function(array){
    return Math.min.apply(Math, array);
};

Some useful functions from the MooTools library:

Function.delay

Used to execute a function after the given milliseconds have elapsed.

// alerts "hello" after 2 seconds.
(function() {
    alert("hello");
}).delay(2000);    ​

Number.times

Similar to Ruby's times method for numbers, this accepts a function and executes it N times where N is the numbers value.

// logs hello 5 times
(5).times(function() {
    console.log("hello");
});
Anurag
A: 

There is a nice article at http://maiaco.com/articles/js/missingArrayFunctions.php describing six helpful functions to add to the Array prototype. The functions are linearSearch (same as indexOf given in another answer), binarySearch, retainAll, removeAll, unique, and addAll. The article also includes the JavaScript code for each of the six functions and example code showing how to use them.

Rex Barzee