Tuesday, May 10, 2011

JavaScript EndsWith Example

javascript does not provide a native function to check whether a string ends 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 endsWith(haystack,needle,isCaseSensitive){
  if(isCaseSensitive){
   haystack=haystack.toUpperCase();
   needle=needle.toUpperCase();
  }
  return haystack.substr(-1*needle.length)==needle?true:false;
 }
Concept of function is fairly simple we first just get the substring of the haystack to the length of the needle(we multiply this length with -1 so that we get substring from the end of the haystack) and then check whether our substring returned is equal to our needle or not.

a sample use would be
// yeilds false
endsWith("tutorialjinni",'jInni',false)

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