Javascript Substring function

Javascript has an inbuilt substring function which helps to extract parts of a string.

substring(start, stop) :

start (mandatory) – The starting index

stop (optional) – The index to stop extraction

Example: If you want to find the first 3 alphabets in the word INDIA, the code would be

var name = “INDIA”;

var firstThreeLetters = name.substring(0,3);

alert(firstThreeLetters);

The alert would display : IND

Note: Here start is 0 hence the extraction starts from the letter in the 0th position i.e. the first letter. The stop index is 3 which means extraction would stop at index 3 (the letter at index 3 will not be extracted)

Since stop is optional, if you only specify the start parameter, all the letters after the starting index (including the one at the start) would be extracted.

Example: Consider the same example as above, for the word INDIA if we were to give the start as 1

var name = “INDIA”;

var extractedLetters = name.substring(1);

alert(extractedLetters);

The alert would display NDIA as the output of the javascript substring method.

————————————————————————————

Indepth Analysis of Javascript substring

Let’s try and create our own Javascript substring function.

String.prototype.mySubstring = function(start,stop) {

var charArray = this.split(’);

var temp = “”;

for(var i=start;<stop;i++)

{

temp = temp + charArray[i];

}

return temp;

}

Now, you can use this function instead of the default substring function. Include the above code in any page and you can use mySubstring inside any javascript function.

Example:

var name = “INDIA”;

var extractedLetters = name.mySubstring(0,3);

alert(extractedLetters);

The alert would display IND thus emulating the real Javascript substring function!

Note: This method is just a food for thought. To help you understand how exactly such methods would be implemented. For all practical purposes use the default substring function of Javascript.

http://www.techtamasha.com/wp-content/plugins/sociofluid/images/digg_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/reddit_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/delicious_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/furl_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/technorati_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/google_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/myspace_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/facebook_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/yahoobuzz_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/twitter_48.png

0 comments ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment