IE11中String的endsWith()方法失效及替代方案咨询
解决IE11中
endsWith方法不支持的问题 这个问题我太熟悉了!IE11本身不支持ES6新增的String.prototype.endsWith()方法,这就是为什么你在Chrome里运行正常,到IE11就报错。不过有几个简单好用的替代方案,我给你整理一下:
方案一:添加Polyfill(推荐,无需修改现有代码)
直接给String原型补上这个方法,这样你原来的this.form.name.endsWith("$END$")代码完全不用改,和原生用法一模一样:
// 先判断浏览器是否已经支持,避免重复定义 if (!String.prototype.endsWith) { String.prototype.endsWith = function(searchString, position) { const subjectString = this.toString(); // 处理position参数的默认值和边界情况 const pos = position === undefined ? subjectString.length : Math.min(position, subjectString.length); const startPos = pos - searchString.length; // 从指定位置开始查找,判断是否匹配 return startPos >= 0 && subjectString.indexOf(searchString, startPos) === startPos; }; }
把这段代码放在你项目的入口文件里,全局生效后所有字符串都能调用endsWith了。
方案二:自定义工具函数(不修改原型,更轻量化)
如果你不想修改String原型,也可以写个独立的工具函数来实现相同逻辑:
方式1:用indexOf判断
function endsWith(str, suffix) { // 计算起始查找位置:字符串长度减去后缀长度 const startIndex = str.length - suffix.length; // 从起始位置开始查找,找到且位置匹配就返回true return startIndex >= 0 && str.indexOf(suffix, startIndex) === startIndex; } // 调用示例 endsWith(this.form.name, "$END$");
方式2:用slice截取比较
这种方式更直观,直接取字符串最后N个字符和后缀对比:
function endsWith(str, suffix) { // 如果原字符串比后缀短,直接返回false if (str.length < suffix.length) return false; // 截取最后suffix.length个字符,和后缀比较 return str.slice(-suffix.length) === suffix; } // 调用示例 endsWith(this.form.name, "$END$");
额外提示
如果你项目里用了Babel、TypeScript这类转译工具,只需要配置好转译目标为ES5,工具会自动把endsWith转译成IE11能识别的代码,省得自己写替代逻辑~
内容的提问来源于stack exchange,提问作者cpp_learner
相关产品推荐
相关产品推荐

