endwith与startwith字符串方法匹配重写

endwith与startwith字符串方法匹配重写

	在js读取文件信息并判断文件的格式类型时出现问题,并找到解决方案,写下来与大家分享,共勉。
									---DanlV	

描述

本人在上传MP3格式文件时,需要判断用户上传的是不是MP3格式文件,但是js-API中并没有类似于java的endwith方法,直接使用会报错,有时各种浏览器版本会出现endwith可以使用,并不是全部。经过自己的一番探索之后,写下了两个封装方法,在这里分享发夹使用。

endwith兼容方法

 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;
 }

startwith兼容方法

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;
 }

实例

两个小实例供大家参考,实验:
1.endwith

var Music = location.href;
if (Music.endWith('MP3'))
{
    //如果当前Music是以 MP3 结束
} 

2.startwith

var Music = location.href;
if (Music.startWith('mp3'))
{
    //如果当前Music是以 MP3 开头
}
原文地址:https://www.cnblogs.com/shenze/p/7143445.html