FE-Interview
FE-Interview copied to clipboard
给 JavaScript 的 String 原生对象添加一个名为 trim 的原型方法,用于截取字符串前后的空白字符
扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。
~(function(){
String.prototype.myTrim = function(){
return this.replace(/^\s*|\s*$/g, '');
}
})();
console.log(' hello world '.myTrim()); // hello world
console.log('abcd '.myTrim()); // abcd
String.prototype.trim = function () {
if (this.length <= 0) {
return "";
}
const that = this;
let left = 0;
let right = that.length - 1;
while (left < that.length) {
if (that[left] !== " ") {
break;
}
left++;
}
while (right > left) {
if (that[right] !== " ") {
break;
}
right--;
}
console.log(`DEBUG: after trim left: ${left} right: ${right}`);
return that.slice(left, right + 1);
};
" hello world ".trim();
String.prototype.mytrim = function () {
return this.replace(/^\s*|\s*$/g, '')
}
let s = ' aaa '
console.log(s.mytrim())