Trim string in JavaScript?

后端 未结 20 2392
不知归路
不知归路 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:16
    String.prototype.trim = String.prototype.trim || function () {
        return this.replace(/^\s+|\s+$/g, "");
    };
    
    String.prototype.trimLeft = String.prototype.trimLeft || function () {
        return this.replace(/^\s+/, "");
    };
    
    String.prototype.trimRight = String.prototype.trimRight || function () {
        return this.replace(/\s+$/, "");
    };
    
    String.prototype.trimFull = String.prototype.trimFull || function () {
        return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, "").replace(/\s+/g, " ");
    };
    

    Shamelessly stolen from Matt duereg.

    0 讨论(0)
  • 2020-11-21 07:18

    Here it is in TypeScript:

    var trim: (input: string) => string = String.prototype.trim
        ? ((input: string) : string => {
            return (input || "").trim();
        })
        : ((input: string) : string => {
            return (input || "").replace(/^\s+|\s+$/g,"");
        })
    

    It will fall back to the regex if the native prototype is not available.

    0 讨论(0)
提交回复
热议问题