javascript中startswith和endsWidth 与 es6中的 startswith 和 endsWidth

在javascript中使用String.startswith和String.endsWidth

一、String.startswith 和 String.endsWidth 功能介绍

  String.startswith:接受一个参数,参数是要检索的字符串。判断当前字符串是否以另一个字符串作为开头。

  String.endsWidth:接受一个参数,参数是要检索的字符串。判断当前字符串是否以另一个字符串结尾。

  例如: 

 1 var result  = "abcd".startsWith("ab"); 
 2 console.log("result:",result);// true
 3 
 4 var result1 = "abcd".startsWith("bc"); 
 5 console.log("result1:",result1);// false
 6 
 7 var result2 = "abcd".endsWith("cd");  
 8 console.log("result2:",result2); // true
 9 
10 var result3 = "abcd".endsWith("e");    
11 console.log("result3:",result3);// false
12 
13 var result4 = "a".startsWith("a");     
14 console.log("result4:",result4);// true
15 
16 var result5 = "a".endsWith("a");       
17 console.log("result5:",result5);// true

  运行结果

    

  注意:

    Javascript中没有自带这两个方法,要想使用可以可以自定义,代码如下:

      ① startsWidth:

if (typeof String.prototype.startsWith != 'function') {
  //在引用类型的原型链上添加这个方法,只需要添加一次,因此进行判断
  String.prototype.startsWith = function (prefix){
    return this.slice(0, prefix.length) === prefix;
  };
}

      ② endsWidth:

1 if (typeof String.prototype.endsWith != 'function') {
2    String.prototype.endsWith = function(suffix) {
3      return this.indexOf(suffix, this.length - suffix.length) !== -1;
4    };
5 }

二、es6中的 

  String.startswith 和 String.endsWidth 功能介绍

    String.startswidth:接收两个参数,第一个参数为检索的值,第二个参数为检索的起始位置(可选),返回布尔值

      String.endsWidth:接收两个参数,第一个参数为检索的值,第二个参数为检索的起始位置(可选),返回布尔值

    例如: 

1 let s = 'Hello world!';
2 
3 const [a, b, c] = [
4     s.startsWith('Hello', 2),
5     s.endsWith('!'),
6     s.includes('o w')
7 ];
8 
9 console.log(a, b, c); // false true true

    运行结果:

      

    

原文地址:https://www.cnblogs.com/mycnblogs-guoguo/p/10522028.html