一、采用正则表达式实现startWith、endWith效果函数
String.prototype.startWith=function(str){
var reg=new RegExp(\"^\"+str);
return reg.test(this);
}
//测试ok,直接使用str.endWith(\"abc\")方式调用即可
String.prototype.endWith=function(str){
var reg=new RegExp(str+\"$\");
return reg.test(this);
}
二、JavaScript实现startWith、endWith效果函数
<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>
//以下是使用示例
var url = location.href;
if (url.startWith(\'http://www.phpstudy.net\'))
{
//如果当前url是以 http://www.phpstudy.net/ 开头
}
本文地址:https://www.stayed.cn/item/22526
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我