Trim string in JavaScript?

后端 未结 20 2408
不知归路
不知归路 2020-11-21 06:27

How do I trim a string in JavaScript? That is, how do I remove all whitespace from the beginning and the end of the string in JavaScript?

20条回答
  •  一向
    一向 (楼主)
    2020-11-21 07:10

    Use the Native JavaScript Methods: String.trimLeft(), String.trimRight(), and String.trim().


    String.trim() is supported in IE9+ and all other major browsers:

    '  Hello  '.trim()  //-> 'Hello'
    


    String.trimLeft() and String.trimRight() are non-standard, but are supported in all major browsers except IE

    '  Hello  '.trimLeft()   //-> 'Hello  '
    '  Hello  '.trimRight()  //-> '  Hello'
    


    IE support is easy with a polyfill however:

    if (!''.trimLeft) {
        String.prototype.trimLeft = function() {
            return this.replace(/^\s+/,'');
        };
        String.prototype.trimRight = function() {
            return this.replace(/\s+$/,'');
        };
        if (!''.trim) {
            String.prototype.trim = function() {
                return this.replace(/^\s+|\s+$/g, '');
            };
        }
    }
    

提交回复
热议问题