首页 > Web开发 > 详细

js判断一个字符串是以某个字符串开头

时间:2018-09-07 15:38:29      阅读:338      评论:0      收藏:0      [点我收藏+]

方法1:

substr() 方法

if("123".substr(0, 2) == "12"){
    console.log(true);
}

方法2:

substring() 方法

if("123".substring(0, 2) == "12"){
    console.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);
}

 

js判断一个字符串是以某个字符串开头

原文:https://www.cnblogs.com/sghy/p/9604813.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!