正则实现 trim 去空格
原型方式
String.prototype.trim = function(){
return this.replace(/(^\s*)|(\s*$)/g, '');
}
String.prototype.ltrim = function(){
return this.replace(/(^\s*)/g, '');
}
String.prototype.rtrim = function(){
return this.replace(/(\s*$)/g, '');
}
console.log('%c%s', 'background: greenyellow;', ' 哈哈哈哈 哈哈哈哈 '.trim() );
console.log('%c%s', 'background: greenyellow;', ' 哈哈哈哈 哈哈哈哈 '.ltrim() );
console.log('%c%s', 'background: greenyellow;', ' 哈哈哈哈 哈哈哈哈 '.rtrim() );
方法封装
function strTrim(str, type = 'a') {
const setting = {
a: /(^\s*)|(\s*$)/g,
l: /(^\s*)/g,
r: /(\s*$)/g,
};
return str.replace(setting[type], '');
}
console.log('%c%s', 'background: greenyellow;', strTrim(' 哈哈哈哈 哈哈哈哈 ', 'a'));
console.log('%c%s', 'background: greenyellow;', strTrim(' 哈哈哈哈 哈哈哈哈 ', 'l'));
console.log('%c%s', 'background: greenyellow;', strTrim(' 哈哈哈哈 哈哈哈哈 ', 'r'));