Tuesday 28 June 2011

Useful javascript snippets

Friquently used javascript snippets.

Replace substring by another one. To replace all occurrences of a string using javascript, 'g' modifier should be used in pattern:
function str_replace(search, replacement, highstack, option) {
     if(typeof(option) != undefined) {
          highstack = highstack.replace(search, replacement);
     } else {
          highstack = highstack.replace(/ + search + /g, replacement);
     }
     return highstack;
}
Usage:
// replace all occurrences in the string
highstack = str_replace(search, replacement, highstack);

// replace first entry of the string
highstack = str_replace(search, replacement, highstack, 'first');
Check if string is integer:
Object.prototype.isInt = function() {
    return parseInt(this) == Number(this) && this.indexOf('.') == -1;
}
var val = '123';
alert(val.isInt());
Shuffle array:
shuffle = function(o){
    for(var j, x, i = o.length; i; 
         j = parseInt(Math.random() * i),
         x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};
Check if email address is valid:
function isEmailValid(email) {
   var reg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
   return reg.test(email);
}
Check if date is valid:
// date format dd:mm:yyyy
function isValidDate(sText) {
    var reDate = /(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/;
    return reDate.test(sText);
}