手写 trim() trimLeft() trimRight()

    String.prototype.trimLeft = function () {
        let str = this;
        for (var i = 0; i < str.length; i++) {
            if (str.charAt(i) !== ' ') {
                return str.substring(i, str.length)
            }
        }
    }
    console.log('    adv    '.trimLeft())

    String.prototype.trimRight = function () {
        let str = this,
            index = 0;
        for (var i = 0; i < str.length; i++) {
            if (str.charAt(i) !== ' ') {
                index = i
            }
        }
        return str.substring(0, index + 1)
    }
    console.log('    adv    '.trimRight())

    String.prototype.trim = function () {
        return this.replace(/(^\s*)|(\s*)$/g, '')
    }
    console.log('    adv    '.trim())

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页