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

时间:2023-03-09 16:06:38
javascript中startswith和endsWidth 与 es6中的 startswith 和 endsWidth

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

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

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

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

  例如: 

 var result  = "abcd".startsWith("ab");
console.log("result:",result);// true var result1 = "abcd".startsWith("bc");
console.log("result1:",result1);// false var result2 = "abcd".endsWith("cd");
console.log("result2:",result2); // true var result3 = "abcd".endsWith("e");
console.log("result3:",result3);// false var result4 = "a".startsWith("a");
console.log("result4:",result4);// true var result5 = "a".endsWith("a");
console.log("result5:",result5);// true

  运行结果

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

  注意:

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

      ① startsWidth:

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

      ② endsWidth:

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

二、es6中的

  String.startswith 和 String.endsWidth 功能介绍

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

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

    例如: 

 let s = 'Hello world!';

 const [a, b, c] = [
s.startsWith('Hello', 2),
s.endsWith('!'),
s.includes('o w')
]; console.log(a, b, c); // false true true

    运行结果:

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