Trim string in JavaScript?

后端 未结 20 2410
不知归路
不知归路 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:07

    Flagrant Badassery has 11 different trims with benchmark information:

    http://blog.stevenlevithan.com/archives/faster-trim-javascript

    Non-surprisingly regexp-based are slower than traditional loop.


    Here is my personal one. This code is old! I wrote it for JavaScript1.1 and Netscape 3 and it has been only slightly updated since. (Original used String.charAt)

    /**
     *  Trim string. Actually trims all control characters.
     *  Ignores fancy Unicode spaces. Forces to string.
     */
    function trim(str) {
        str = str.toString();
        var begin = 0;
        var end = str.length - 1;
        while (begin <= end && str.charCodeAt(begin) < 33) { ++begin; }
        while (end > begin && str.charCodeAt(end) < 33) { --end; }
        return str.substr(begin, end - begin + 1);
    }
    

提交回复
热议问题