js判断⼀个字符串以某个字符串开头⽅法1:
substr() ⽅法
if("123".substr(0,2)=="12"){
console.log(true);
}
⽅法2:
substring() ⽅法
if("123".substring(0,2)=="12"){
substring和sliceconsole.log(true);
}
⽅法3:
slice()⽅法
if("123".slice(0,2)=="12"){
console.log(true);
}
⽅法4:
indexOf() ⽅法
if("123".indexOf("12")==0){
console.log(true);
}
⽅法5:
startsWith(),endsWith(),不过兼容不好
console.log("123".startsWith("12"));//true
console.log("123".endsWith("23")); //true
// 兼容
if(typeof String.prototype.startsWith !='function'){
String.prototype.startsWith=function(prefix){
return this.slice(0, prefix.length)=== prefix;
};
}
⽅法6:
正则
if("123".search("12")!=-1){
console.log(true);
}
if(new RegExp("^12.*$").test(12)){
console.log(true);
}
if("12".match(new RegExp("^12.*$"))){
console.log(true);
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。