《献给你,我深爱的ECMAScript》之String篇

本文主要说说ECMAScript6中新引入的String的api

第一个:startsWith

从语义化上不难知道:是判定某个指定的字符串是否从某个子字符开始的。

语法:

  var startsWith = str.startsWith(searchString [,position]);  

示例:

  var str = "zhangyaochun for w3cplus";
  str.startsWith("zhang"); //true
  str.startsWith("Zhang"); //false

评语:

其实现在流行的很多类库也有类似这样的api,我们来看看如果封装的?

  //kissy 1.3
  function startsWith(str,prefix){
      return str.lastIndexOf(prefix,0) === 0;
  }

  //prototype 1.7
  //http://api.prototypejs.org/language/String/prototype/startsWith/
  function startsWith(pattern,position){
      //严谨的参数控制
      position = Object.isNumber(position) ? position : 0;
      return this.lastIndexOf(pattern,position) === position;
  }  

第二个:endsWith

从语义化上也不难知道:是判定某个指定的字符串是否从某个子字符结束的

语法:

  var endsWith = str.endsWith(searchString [,position]);    

示例:

  var str = "zhangyaochun for w3cplus";
  str.endsWith("w3cplus"); //true
  str.endsWith("W3cplus"); //false  

评语:

其实现在流行的很多类库也有类似这样的api,我们来看看如果封装的?

  //prototype 1.7
  //http://api.prototypejs.org/language/String/prototype/endsWith/
  function endsWith(pattern){
       var d = this.length - pattern.length;
       return d >= 0 && this.indexOf(pattern,d) === d;
  }

  //kissy 1.3
  function endsWith(str,suffix){
       //会判定字串与指定的字符串的长度对比
       var ind = str.length - suffix.length;
       return ind >= 0 && str.indexOf(suffix,ind) == ind;
  }

两个方案基本一样,只是我更喜欢严谨的 ===

第三个:contains

从语义化上也不难知道:是判定某个指定的字符串是否含有另一个子字符串

语法:

  var contained = str.contains(searchString [,position]);

示例:

  var str = "zhangyaochun for w3cplus";
  str.contains("w3cplus"); //true
  str.contains("zhangyaochun"); //true
  str.contains("you");  //false  

评语:

其实现在流行的很多类库也有类似这样的api,我们来看看如果封装的?

  //prototype 1.7
  //http://api.prototypejs.org/language/String/prototype/include/
  function include(pattern){
      this.indexOf(pattern) > -1;
  }

第四个:repeat

从语义化上也不能知道:是判定某个指定的字符串是否含有另一个子字符串

语法:

  var newString = str.repeat(count);  

示例:

  var str = "zhangyaochun for w3cplus";
  str.repeat(2); //"zhangyaochun for w3cpluszhangyaochun for w3cplus"  

评语:

其实现在流行的很多类库也有类似这样的api,我们来看看如果封装的?

  //prototype 1.7
  //http://api.prototypejs.org/language/String/prototype/times/
  function times(count){
      //有一层判定
      return count < 1 ? '' : new Array(count +1).join(this);
  }

 

如需转载,烦请注明出处:http://www.w3cplus.com/js/ecmascript-lesson-5.html

返回顶部