How to Remove All White Space from the Beginning or End of a String

How to remove all white space from the beginning or end of a string?

String.Trim() returns a string which equals the input string with all white-spaces trimmed from start and end:

"   A String   ".Trim() -> "A String"

String.TrimStart() returns a string with white-spaces trimmed from the start:

"   A String   ".TrimStart() -> "A String   "

String.TrimEnd() returns a string with white-spaces trimmed from the end:

"   A String   ".TrimEnd() -> "   A String"

None of the methods modify the original string object.

(In some implementations at least, if there are no white-spaces to be trimmed, you get back the same string object you started with:

csharp> string a = "a";
csharp> string trimmed = a.Trim();
csharp> (object) a == (object) trimmed;
returns true

I don't know whether this is guaranteed by the language.)

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

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

How do I remove white-space from the beginning of a string?

You could use:

temp = temp.replaceFirst("^\\s*", "")

How do I remove whitespace from the end of a string in Python?

>>> "    xyz     ".rstrip()
' xyz'

There is more about rstrip in the documentation.

How to remove a white space at the end of a string in java?

If you just want to trim whitespace at the end, use String#replaceAll() with an appropriate regex:

String input = " XXXX ";
String output = input.replaceAll("\\s+$", "");
System.out.println("***" + input + "***"); // *** XXXX ***
System.out.println("***" + output + "***"); // *** XXXX***

If you really want to replace just one whitespace character at the end, then replace on \s$ instead of \s+$.

Remove all whitespace in a string

If you want to remove leading and ending spaces, use str.strip():

>>> "  hello  apple  ".strip()
'hello apple'

If you want to remove all space characters, use str.replace() (NB this only removes the “normal” ASCII space character ' ' U+0020 but not any other whitespace):

>>> "  hello  apple  ".replace(" ", "")
'helloapple'

If you want to remove duplicated spaces, use str.split() followed by str.join():

>>> " ".join("  hello  apple  ".split())
'hello apple'

Remove white spaces from the beginning of each string in a list

Use str.lstrip in a list comprehension:

my_list = [' a', ' b', ' c']

my_list = [i.lstrip() for i in my_list]
print(my_list) # ['a', 'b', 'c']

removing white spaces at beginning and end of string

Your string contains not only whitespace but also new line characters.

Use stringByTrimmingCharactersInSet with whitespaceAndNewlineCharacterSet.

let string = "\r\n\t- Someone will come here?\n- I don't know for sure...\r\n\r\n"
let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

In Swift 3 it's more cleaned up:

let trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)


Related Topics



Leave a reply



Submit