mozilla
您的搜索结果

    String.prototype.startsWith()

    该特性处于 ECMAScript 6 规范草案中,目前的实现在未来可能会发生微调,请谨慎使用。

    概述

    startsWith()方法用来判断当前字符串是否是以另外一个给定的子字符串“开头”的,根据判断结果返回 truefalse

    语法

    str.startsWith(searchString [, position]);

    参数

    searchString
    要搜索的子字符串。
    position
    str 中搜索 searchString 的开始位置,默认值为 0,也就是真正的字符串开头处。

    示例

    var str = "To be, or not to be, that is the question.";
    
    alert(str.startsWith("To be"));         // true
    alert(str.startsWith("not to be"));     // false
    alert(str.startsWith("not to be", 10)); // true

    Polyfill

    /*! http://mths.be/startswith v0.2.0 by @mathias */
    if (!String.prototype.startsWith) {
      (function() {
        'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
        var defineProperty = (function() {
          // IE 8 only supports `Object.defineProperty` on DOM elements
          try {
            var object = {};
            var $defineProperty = Object.defineProperty;
            var result = $defineProperty(object, object, object) && $defineProperty;
          } catch(error) {}
          return result;
        }());
        var toString = {}.toString;
        var startsWith = function(search) {
          if (this == null) {
            throw TypeError();
          }
          var string = String(this);
          if (search && toString.call(search) == '[object RegExp]') {
            throw TypeError();
          }
          var stringLength = string.length;
          var searchString = String(search);
          var searchLength = searchString.length;
          var position = arguments.length > 1 ? arguments[1] : undefined;
          // `ToInteger`
          var pos = position ? Number(position) : 0;
          if (pos != pos) { // better `isNaN`
            pos = 0;
          }
          var start = Math.min(Math.max(pos, 0), stringLength);
          // Avoid the `indexOf` call if no match is possible
          if (searchLength + start > stringLength) {
            return false;
          }
          var index = -1;
          while (++index < searchLength) {
            if (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {
              return false;
            }
          }
          return true;
        };
        if (defineProperty) {
          defineProperty(String.prototype, 'startsWith', {
            'value': startsWith,
            'configurable': true,
            'writable': true
          });
        } else {
          String.prototype.startsWith = startsWith;
        }
      }());
    }

    浏览器兼容性

    Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
    Basic support 未实现 17 (17) 未实现 未实现 未实现
    Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
    Basic support 未实现 未实现 17.0 (17) 未实现 未实现 未实现

    相关链接

    文档标签和贡献者

    此页面的贡献者有: ziyunfei, teoli, zhangyaochun1987
    最后编辑者: ziyunfei,
    隐藏侧边栏