Javascript - How to remove the white space at the start of the string

后端 未结 9 1413
清酒与你
清酒与你 2020-12-15 06:20

I want to remove the white space which is there in the start of the string It should remove only the space at the start of the string, other spaces should be there.

相关标签:
9条回答
  • 2020-12-15 06:47

    This is what you want:

    function ltrim(str) {
      if(!str) return str;
      return str.replace(/^\s+/g, '');
    }
    

    Also for ordinary trim in IE8+:

    function trimStr(str) {
      if(!str) return str;
      return str.replace(/^\s+|\s+$/g, '');
    }
    

    And for trimming the right side:

    function rtrim(str) {
      if(!str) return str;
      return str.replace(/\s+$/g, '');
    }
    

    Or as polyfill:

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

    Note:
    \s: includes spaces, tabs \t, newlines \n and few other rare characters, such as \v, \f and \r.
    \uFEFF: Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
    \xA0: ASCII 0xA0 (160: non-breaking space) is not recognised as a space character

    0 讨论(0)
  • 2020-12-15 06:49

    Easiest solution: (ES10 feature trimStart())

    var string= 'This is a test';
    console.log(string.trimStart());
    
    0 讨论(0)
  • 2020-12-15 06:53

    Just a different and a not so efficient way to do it

    var str = "   My string";
    
    function trim() {
      var stringStarted = false;
      var newString = "";
    
      for (var i in str) {
        if (!stringStarted && str[i] == " ") {
          continue;
        }
        else if (!stringStarted) {
          stringStarted = true;
        }
        newString += str[i];
      }
      
      return newString;
    }
    
    console.log(trim(str));

    I am really sure this doesn't work for anything else and is not the most optimum solution, but this just popped into my mind

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