Skip to content

手写字符串 trim 方法,保证浏览器的兼容性

js
console.log(typeof String.prototype.myTrim);
// 兼容性处理
if (typeof String.prototype.myTrim !== 'function') {
  //(涉及原型,this,正则表达式)
  String.prototype.myTrim = function () {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  };
}
console.log(typeof String.prototype.myTrim);
const str = ' abc ';
console.log(str.myTrim());

基于 MIT 许可发布