Monday, May 9, 2011

JavaScript StartsWith Example

javascript tutorial
javascript does not provide a native function to check whether a string starts with a specific string or not, to do this functionality we have to write a very simple function of our own. The concept of this function is fairly simple, we need two strings say one is haystack and other is needle and one boolean to check whether we want case-sensitive comparison on strings or not, our function would be like this,
 function startsWith(haystack,needle,isCaseSensitive){
  
  if(isCaseSensitive){
   
   haystack=haystack.toUpperCase();
   needle=needle.toUpperCase();
   
  }
  
  return haystack.substr(0,needle.length)==needle?true:false;
 }
an example use of a the above function will be
startsWith("tutorialjinni",'tutorial',true);
// true

startsWith("tutorialjinni",'Tutorial',false);
// false

hope this function will be handy...

0 comments:

Post a Comment

 

Blog Info

A Pakistani Website by Originative Systems

Total Pageviews

Tutorial Jinni Copyright © 2015 WoodMag is Modified by Originative Systems