JavaScript trim 完成(去除字符串首尾指定字符)

javascriptString.prototype.trim = function (char, type) {
    if (char) {
        if (type == 'left') {
            return this.replace(new RegExp('^\\'+char+'+', 'g'), '');
        } else if (type == 'right') {
            return this.replace(new RegExp('\\'+char+'+$', 'g'), '');
        }
        return this.replace(new RegExp('^\\'+char+'+|\\'+char+'+$', 'g'), '');
    }
    return this.replace(/^\s+|\s+$/g, '');
};


// 去除字符串首尾的悉数空缺
var str = ' Ruchee ';
console.log('xxx' + str.trim() + 'xxx');  // xxxRucheexxx


// 去除字符串左边空缺
str = ' Ruchee ';
console.log('xxx' + str.trim(' ', 'left') + 'xxx');  // xxxRuchee xxx


// 去除字符串右边空缺
str = ' Ruchee ';
console.log('xxx' + str.trim(' ', 'right') + 'xxx');  // xxx Rucheexxx


// 去除字符串两侧指定字符
str = '/Ruchee/';
console.log(str.trim('/'));  // Ruchee


// 去除字符串左边指定字符
str = '/Ruchee/';
console.log(str.trim('/', 'left'));  // Ruchee/


// 去除字符串右边指定字符
str = '/Ruchee/';
console.log(str.trim('/', 'right'));  // /Ruchee
    原文作者:Ruchee
    原文地址: https://segmentfault.com/a/1190000002438098
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞