javascript中的startWith和endWith的几种实现方法

  JavaScript采用正则表达式实现startWith、endWith效果函数

  

复制代码 代码如下:

  String.prototype.startWith=function(str){

  var reg=new RegExp("^"+str);

  return reg.test(this);

  }

  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.glzy8.com'))

  {

  //如果当前url是以 http://www.glzy8.com/ 开头

  }

  另外一种即是用indexOf实现:

  

复制代码 代码如下:

  var index = str.indexOf('abc');

  if(index==0){

  //以'abc'开头

  }