【问题标题】:startsWith method not supported in IE any replacement for this? [duplicate]IE 中不支持startsWith 方法有任何替代方法吗? [复制]
【发布时间】:2016-12-10 22:05:54
【问题描述】:
var s = "Main String";
s.startsWith("Main");

用类似的逻辑或任何其他对所有浏览器通用的方法替换 startWith。

【问题讨论】:

  • docs 包含一个 polyfill。
  • 通常情况下,您应该在 在这里提出问题之前用 Google 搜索。
  • 是的,你真的应该先用谷歌搜索一下。

标签: javascript internet-explorer


【解决方案1】:

startsWith 的一个很好的替代品是使用s.substring(0, 4) == 'Main'

这应该可行,所以继续尝试吧。

【讨论】:

  • 它的编码非常硬。
【解决方案2】:

在String中添加原型方法:

String.prototype.myStartsWith = function(str){
 if(this.indexOf(str)===0){
  return true;
 }else{
   return  false;
 }
};

现在打电话:

s.myStartsWith("Main");

【讨论】:

  • 反对这样做的原因是它不如其他解决方案效率高吗?
  • 记得在覆盖前检查是否存在:if (!String.prototype.startsWith) { String.prototype.startsWith = function(searchString, position){ return this.substr(position || 0, searchString.length) === searchString; }; }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-14
  • 2013-06-22
  • 1970-01-01
相关资源
最近更新 更多