Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Saturday, December 11, 2010

javascript Date difference in days

Many times it is required to compare two Date object and get the difference between the dates in days. Following javascript function will get you the difference in days

Date.getDaysDifference = function(fromDate,toDate)
{
   fromDate = new Date(fromDate.getFullYear(),fromDate.getMonth(),fromDate.getDate());
   toDate = new Date(toDate.getFullYear(),toDate.getMonth(),toDate.getDate());
   return ((toDate-fromDate)/86400000); //Total millisends in day =1000*60*60*24
}

Date.prototype.getDaysDifference = function(toDate)
{
   return Date.getDaysDifference(this,toDate);
}


Usage Example

var fromDate= new Date(2010,1,1);
var toDate= new Date(); //today's date
alert(Date.getDaysDifference(fromDate,toDate));
//or
alert(fromDate.getDaysDifference(toDate));

Wednesday, November 10, 2010

Javascript injections and Javascript debugging techniques.

Javascript injection is a technique of executing javascript in already loaded page in a browser. JS injections are commonly used for executing XSS(cross side scripting), SQL injection, for bypassing client side validations and also for debugging javascript in webpages.
There are many approach by which we can execute a javascript injection, few of them are shown here

1. Query inside address bar (works in almost all brower): Like we write javascript statement in anchor href attribute which gets executed on click of anchor. In the same way we can put javascript in address bar and execute them.

E.g. Copy and paste below given line in address bar and press enter
javascript: alert("This is a simple js injection.");
we can also add a js function using js injection like
javascript: void(window.myfunc = function(){alert("This alert is shown via myfunc function.");}); func();

2. Using browser js debugger: Almost all modern browser have there debugger for the web developers. Like IE Developer Tools (which comes with IE8 and onwards), firebug in Mozilla, Dragonfly in Opera. These all tools have a javascipt console where we can write javascript and execute them. Using these tools we can even write multiline javascript.

Tuesday, November 17, 2009

C# like trim(),trimStart(),trimEnd() function in javascript

String.prototype.trimStart=function(c)
{
c = c?c:' ';
var i=0;
for(;i<this.length && this.charAt(i)==c; i++);
return this.substring(i);
}
String.prototype.trimEnd=function(c)

{
c = c?c:' ';
var i=this.length-1;
for(;i>=0 && this.charAt(i)==c;i--);
return this.substring(0,i+1);
}
String.prototype.trim=function(c)
{
return this.trimStart(c).trimEnd(c);
}
Example:
" anil soni ".trim()