Trim string in JavaScript?

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

    use simply code

    var str = "       Hello World!        ";
    alert(str.trim());
    

    Browser support

    Feature         Chrome  Firefox Internet Explorer   Opera   Safari  Edge
    Basic support   (Yes)   3.5     9                   10.5    5       ?
    

    For old browser add prototype

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

提交回复
热议问题