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

方法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);
}

 

posted @ 2018-09-07 15:17  枫叶布  阅读(121883)  评论(0编辑  收藏  举报