Fetch GET parameters in JS/jQuery

If you have a URL with some GET parameters as follows:

www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 

and need to get the values of each parameters then below is a nifty piece of code solving your requirement.

JavaScript has nothing built in for handling query string parameters.

You could access location.search, which would give you from the ? character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.

You can then access QueryString.c

Classes in Javascript

Source : >http://www.phpied.com/3-ways-to-define-a-javascript-class/

3 ways to define a JavaScript class

Introduction

JavaScript is a very flexible object-oriented language when it comes to syntax. In this article you can find three ways of defining and instantiating an object. Even if you have already picked your favorite way of doing it, it helps to know some alternatives in order to read other people’s code.

It’s important to note that there are no classes in JavaScript. Functions can be used to somewhat simulate classes, but in general JavaScript is a class-less language. Everything is an object. And when it comes to inheritance, objects inherit from objects, not classes from classes as in the “class”-ical languages.

1. Using a function

This is probably one of the most common ways. You define a normal JavaScript function and then create an object by using the new keyword. To define properties and methods for an object created using function(), you use the this keyword, as seen in the following example.

function Apple (type) {
this.type = type;
this.color = "red";
this.getInfo = getAppleInfo;
}

// anti-pattern! keep reading...
function getAppleInfo() {
return this.color + ' ' + this.type + ' apple';
}

To instantiate an object using the Apple constructor function, set some properties and call methods you can do the following:

var apple = new Apple('macintosh');
apple.color = "reddish";
alert(apple.getInfo());

1.1. Methods defined internally

In the example above you see that the method getInfo() of the Apple “class” was defined in a separate function getAppleInfo(). While this works fine, it has one drawback – you may end up defining a lot of these functions and they are all in the “global namespece”. This means you may have naming conflicts if you (or another library you are using) decide to create another function with the same name. The way to prevent pollution of the global namespace, you can define your methods within the constructor function, like this:

function Apple (type) {
this.type = type;
this.color = "red";
this.getInfo = function() {
return this.color + ' ' + this.type + ' apple';
};
}

Using this syntax changes nothing in the way you instantiate the object and use its properties and methods.

1.2. Methods added to the prototype

A drawback of 1.1. is that the method getInfo() is recreated every time you create a new object. Sometimes that may be what you want, but it’s rare. A more inexpensive way is to add getInfo() to the prototype of the constructor function.

function Apple (type) {
this.type = type;
this.color = "red";
}

Apple.prototype.getInfo = function() {
return this.color + ' ' + this.type + ' apple';
};

Again, you can use the new objects exactly the same way as in 1. and 1.1.

2. Using object literals

Literals are shorter way to define objects and arrays in JavaScript. To create an empty object using you can do:

var o = {};

instead of the “normal” way:

var o = new Object();

For arrays you can do:

var a = [];

instead of:

var a = new Array();

So you can skip the class-like stuff and create an instance (object) immediately. Here’s the same functionality as described in the previous examples, but using object literal syntax this time:

var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
}

In this case you don’t need to (and cannot) create an instance of the class, it already exists. So you simply start using this instance.

apple.color = "reddish";
alert(apple.getInfo());

Such an object is also sometimes called singleton. It “classical” languages such as Java, singleton means that you can have only one single instance of this class at any time, you cannot create more objects of the same class. In JavaScript (no classes, remember?) this concept makes no sense anymore since all objects are singletons to begin with.

3. Singleton using a function

Again with the singleton, eh?

The third way presented in this article is a combination of the other two you already saw. You can use a function to define a singleton object. Here’s the syntax:

var apple = new function() {
this.type = "macintosh";
this.color = "red";
this.getInfo = function () {
return this.color + ' ' + this.type + ' apple';
};
}

So you see that this is very similar to 1.1. discussed above, but the way to use the object is exactly like in 2.

apple.color = "reddish";
alert(apple.getInfo());

new function(){…} does two things at the same time: define a function (an anonymous constructor function) and invoke it with new. It might look a bit confusing if you’re not used to it and it’s not too common, but hey, it’s an option, when you really want a constructor function that you’ll use only once and there’s no sense of giving it a name.

You saw three (plus one) ways of creating objects in JavaScript. Remember that (despite the article’s title) there’s no such thing as a class in JavaScript. Looking forward to start coding using the new knowledge? Happy JavaScript-ing!

More about regular expressions in Javascript

Aah !! Regular expressions

I have got confused most of the times, I need to escape special characters when specifying a regular expression.

Let us take an example of simple date format
dd/mm/yyyy

There are two ways, you can specify your regular expression

// Please note that your regular expression literal object must be surrounded
// between forward slashes as is done below.

// Since forward slash (/) has a special meaning in regular expressions
// it need to be escaped by a backslash ()
var regex = /^d{2}/d{2}/d{4}$/
regex.test("01/04/1975");

/* / -- Used to signify that a regex literal follows.
* ^ - Starts with
* d{2} - 2 digits (date)
* / - Escaping the forward slash
* d{2} - 2 digits (Month)
* / - Escaping the forward slash
* d{4} - 4 digits (Year)
* $ - end of string.
* / - specifies the end of regex literal.
*/

// Things become more complex when you want to specify
// regular expression in a String

// Please note the difference between the regex literal and the string regex
// Here we have to escape the backslash as well.
// So the number of backslashes are doubled.

var regex = new RegExp("^\d{2}\/\d{2}\/\d{4}");


/*
* ^ - Starts with
* \d{2} - 2 digits (date)
* \/ - Escaping the forward slash
* \d{2} - 2 digits (Month)
* \/ - Escaping the forward slash
* \d{4} - 4 digits (Year)
* $ - end of regex.
*/

Please note that you have to escape all those characters which have a special meaning in Regular expressions.
Just place a backslash before that character. (2 backslashes if you are specifying regex as a string literal)
List of characters that need to be escaped are :

[, ], ., ?, *, +, /, , {, }, |, (, )

Related Post : http://javakafunda.blogspot.com/2011/06/10-java-regular-expression-examples-you.html

How to expand collapse (toggle) div layer using jQuery

Thanks to http://designgala.com/how-to-expand-collapse-toggle-div-layer-using-jquery

In almost all of my projects, I have been using jQuery to toggle the layer. So, I thought of sharing how easy it is to expand div layer and collapse panel using jQuery. When user clicks on the header, the content gets displayed by sliding down and when you again click on the header, the content collapses.

Step 1: Include jQuery Library in head section of your html file.

Step 2:

Come up with your own html elements in body section. I chose div ‘layer1′ to be the main container where collapsible/expandable content would reside.

Next, class ‘heading’ is given to header while div ‘content’ holds the show hide layer for that heading


Header-1


Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit

Header-2


Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit

Header-3


Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit

Step 3:

CSS: Now it totally depends on you to write css for your heading, div. Here’s my version of CSS for this example.

.layer1 {
margin: 0;
padding: 0;
width: 500px;
}

.heading {
margin: 1px;
color: #fff;
padding: 3px 10px;
cursor: pointer;
position: relative;
background-color:#c30;
}
.content {
padding: 5px 10px;
background-color:#fafafa;
}
p { padding: 5px 0; }

Step 4:

Again lets go to head section to add few more javascript codes.


jQuery(document).ready(function() {
jQuery(".content").hide();
//toggle the componenet with class msg_body
jQuery(".heading").click(function()
{
jQuery(this).next(".content").slideToggle(500);
});
});

Thats it!! Expandible-Collapsible panel is ready.

What? You want to see a demo…….This post is the demo in itself 🙂

Caution: When using this in blogger

Because the blogger already has a div with class content which is the parent of all the divs in the page. Hence You need to rename the content class to some other suitable name, before you try to use it with blogger.

How to replace in Javascript, when replacement string is a variable

How to replace in Javascript, when replacement string is a variable

Very often we use replace method in javascript while replacing a string literal by another string literal.
But what if we need to replace a string whose value is held in a variable.

Here is the solution…

You can use a regular expression (often referred to as a RegEx or a RegExp). Regular expressions are much more powerful than standard string matching as they can use very complicated logic

// Let's take a look at the above example using regular expressions.
strReplaceSimple = strText.replace( new RegExp( "th", "" ), "[X]" );

alert( strReplaceSimple );

As you can see, we have the same replace happening. So let’s take a look at what’s going on. Instead of passing simple target string to the replace() method, we are passing in a regular expression (new RegExp()) object instance. The RegExp() takes two arguments, the expression and the search flags (left blank in our example). There are two universally valid flags: [g] which means globally replace and [i] which
means case INsensitive. By default, the regular expression is NOT global and case sensitive.

// So let's try to do a global replace using regular expressions.
strReplaceAll = strText.replace( new RegExp( "th", "g" ), "[X]" );

alert( strReplaceAll );

We just did a global replace in ONE line of code.

strReplaceAll = strText.replace( new RegExp( "th", "gi" ), "[X]" );

alert( strReplaceAll );

We just replaced out that additional “Th” simply by adding the flag [i] into the regular expression. That’s how powerful regular expressions are. But there’s more. Regular expressions are more than just flags. Much more!

Image that for some reason, you knew about regular expressions, but you didn’t know about the case insensitive flag [i]. You could have performed the same replace using this:

strReplaceAll = strText.replace( new RegExp( "(T|t)(H|h)", "g" ), "[X]" );

alert( strReplaceAll );

This groups the two letters together, and for each letter it tells the replacing algorithm to match t OR T followed by h OR H. There is sooo much more that regular expressions can do. Unfortunately, that is outside the scope of this entry. You should really look into regular expression both in Javascript and in ColdFusion / Java. They are amazing.

But what happens if you don’t want to do a simple replace? The replace method allows some very interesting flexibility. Up until now, we have been passing a simple string in a the “replace-in” argument ([X]). But, you don’t have to. You can pass in a function pointer instead.

For this example, let’s replace out the target string with a random letter in the brackets, not necessarily the X. First we have to create a function that will return the resultant random string

function RandomString(){
// Create an array of letters.
var arrLetters = ["A","B","C","D","E","V","W","X","Y","Z"];

// Use the random() method and the modulus (%) operator to
// pick a random letter from the above array.
var intLetter = (Math.floor( Math.random() * 10 ) % 9);

// Return the random letter string we get from the
// array of letters above.
return( "[" + arrLetters[ intLetter ] + "]" );
}

Try calling the function on its own a few times, just to see how it behaves.

alert(
RandomString() + "n" + RandomString() + "n" +
RandomString() + "n" + RandomString() + "n" +
RandomString() + "n" + RandomString() + "n" +
RandomString() + "n" + RandomString() + "n"
);

As you can see, it randomly (as random as possible) picks a letter to return. Now, let’s call the replace with the RandomString() method sent as the second argument. We will do this a few times so you can see the randomness in effect.

alert( strText.replace( "th", RandomString ) );
alert( strText.replace( "th", RandomString ) );
alert( strText.replace( "th", RandomString ) );

Notice that we are passing in a POINTER to the function but not actually calling it. RandomString vs. RandomString(). There’s one thing I did not mention yet. Not only can you pass in a function as an argument, but when the replace method is taking place, it passes in the target match as an argument to this function. We could have re-written the function as such:

function RandomString2( strTargetInstance) // This is the target string match instance.
{
var arrLetters = ["A","B","C","D","E","V","W","X","Y","Z"];
var intLetter = (Math.floor( Math.random() * 10 ) % 9);

// Return the random letter string we get from the
// array of letters above. This time, though, we are
// going to include the target string to demonstrate
// that it has been passed in.
return( "[" + strTargetInstance + " : " + arrLetters[ intLetter ] + "]" );
}

Now, we will run it again, just once, so you can see it in action.

alert( strText.replace( "th", RandomString2 ) );

Want to read more on this? do VISIT HERE