Search code examples
javastringtrim

how to only trim the blanks in the beginning of a string


Java method: String.trim() trim blanks (white space, new line, etc.) at both the beginning and end of a string.

How to only trim the blanks in the beginning of a String?


Solution

  • You can with this:

    myString = myString.replaceAll("^\\s+", "")
    

    If you want to remove only specific whitespaces (such as, only blanks), you would replace \\s with either the specific character (eg: "^ +" for only blanks) or the character class (eg: "^[ \\t]+" for blanks and tabs).

    Edit As per @Pshemo's remark, you can use replaceFirst instead of replaceAll.