Javascript customizes the methods startWith of and endWith of

  • 2020-03-27 00:00:15
  • OfStack

One, the use of regular expressions to achieve startWith, endWith effect function
 
String.prototype.startWith=function(str){ 
var reg=new RegExp("^"+str); 
return reg.test(this); 
} 
//Test ok by calling STR. EndWith (" ABC ") directly
String.prototype.endWith=function(str){ 
var reg=new RegExp(str+"$"); 
return reg.test(this); 
} 

Second, JavaScript implementation of startWith, endWith effect function
 
<script type="text/javascript"> 
String.prototype.endWith=function(s){ 
if(s==null||s==""||this.length==0||s.length>this.length) 
return false; 
if(this.substring(this.length-s.length)==s) 
return true; 
else 
return false; 
return true; 
} 
String.prototype.startWith=function(s){ 
if(s==null||s==""||this.length==0||s.length>this.length) 
return false; 
if(this.substr(0,s.length)==s) 
return true; 
else 
return false; 
return true; 
} 
</script> 
//Here is an example of how to use it
var url = location.href; 
if (url.startWith('//www.jb51.net')) 
{ 
// If the current url Based on  //www.jb51.net/  At the beginning  
} 

Related articles: