Trim string in JavaScript?

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

    Although there are a bunch of correct answers above, it should be noted that the String object in JavaScript has a native .trim() method as of ECMAScript 5. Thus ideally any attempt to prototype the trim method should really check to see if it already exists first.

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

    Added natively in: JavaScript 1.8.1 / ECMAScript 5

    Thus supported in:

    Firefox: 3.5+

    Safari: 5+

    Internet Explorer: IE9+ (in Standards mode only!) http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more.aspx

    Chrome: 5+

    Opera: 10.5+

    ECMAScript 5 Support Table: http://kangax.github.com/es5-compat-table/

提交回复
热议问题