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

后端 未结 9 1412
清酒与你
清酒与你 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:31
    var string=' This is test';    
    $.trim(string);
    
    0 讨论(0)
  • 2020-12-15 06:34

    You want to remove the space (i.e whitespace) at the beginning of the string. So, could not use standard jquesy .trim(). You can use the regex to find and replace the whitespace at the beginning of the string.

    Try this:

    .replace(/^\s+/g, "")
    

    Read this post

    Try this:

    var string='    This is test   ';
    alert(string.replace(/^\s+/g, ""));
    

    Working Example

    OR if you want to remove the whitespace from the beginning and end then use .trim()

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

    You should use javascript trim function

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

    This function can also remove white spaces from the end of the string.

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

    You can use String.prototype.trimStart(). Like this:

    myString=myString.trimStart();
    

    An if you want to trim the tail, you can use:

    myString=myString.trimEnd();
    

    Notice, this 2 functions are not supported on IE. For IE you need to use polyfills for them.

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

    .trimLeft() can be used for this.

    const str = "   string   ";
    console.log(str.trimLeft());     // => "string   "
    
    0 讨论(0)
  • 2020-12-15 06:41

    Try to use javascript's trim() function, Basically it will remove the leading and trailing spaces from a string.

    var string=' This is test';
    string = string.trim();
    

    DEMO

    So as per the conversation happened in the comment area, in order to attain the backward browser compatibility just use jquery's $.trim(str)

    var string=' This is test';    
    string = $.trim(string)
    
    0 讨论(0)
提交回复
热议问题