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 whitespace from a string in typescript?
Problem
The trim() method removes whitespace from both sides of a string.
Source
Solution
You can use a Javascript replace method to remove white space like
"hello world".replace(/\s/g, "");
Example
var out = "hello world".replace(/\s/g, "");console.log(out);
How do I trim whitespace?
For whitespace on both sides, use str.strip
:
s = " \t a string example\t "
s = s.strip()
For whitespace on the right side, use str.rstrip
:
s = s.rstrip()
For whitespace on the left side, use str.lstrip
:
s = s.lstrip()
You can provide an argument to strip arbitrary characters to any of these functions, like this:
s = s.strip(' \t\n\r')
This will strip any space, \t
, \n
, or \r
characters from both sides of the string.
The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try re.sub
:
import re
print(re.sub('[\s+]', '', s))
That should print out:
astringexample
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)
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'
How do I trim leading/trailing whitespace in a standard way?
If you can modify the string:
// Note: This function returns a pointer to a substring of the original string.
// If the given string was allocated dynamically, the caller must not overwrite
// that pointer with the returned value, since the original pointer must be
// deallocated using the same allocator with which it was allocated. The return
// value must NOT be deallocated using free() etc.
char *trimwhitespace(char *str)
{
char *end;
// Trim leading space
while(isspace((unsigned char)*str)) str++;
if(*str == 0) // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while(end > str && isspace((unsigned char)*end)) end--;
// Write new null terminator character
end[1] = '\0';
return str;
}
If you can't modify the string, then you can use basically the same method:
// Stores the trimmed input string into the given output buffer, which must be
// large enough to store the result. If it is too small, the output is
// truncated.
size_t trimwhitespace(char *out, size_t len, const char *str)
{
if(len == 0)
return 0;
const char *end;
size_t out_size;
// Trim leading space
while(isspace((unsigned char)*str)) str++;
if(*str == 0) // All spaces?
{
*out = 0;
return 1;
}
// Trim trailing space
end = str + strlen(str) - 1;
while(end > str && isspace((unsigned char)*end)) end--;
end++;
// Set output size to minimum of trimmed string length and buffer size minus 1
out_size = (end - str) < len-1 ? (end - str) : len-1;
// Copy trimmed string and add null terminator
memcpy(out, str, out_size);
out[out_size] = 0;
return out_size;
}
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+$
.
Trim only trailing whitespace from end of string in Swift 3
With regular expressions:
let string = " example "
let trimmed = string.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression)
print(">" + trimmed + "<")
// > example<
\s+
matches one or more whitespace characters, and $
matches
the end of the string.
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
Related Topics
Get HTML Source of Webelement in Selenium Webdriver Using Python
Programmatically Generate Video or Animated Gif in Python
Comparing Two Dictionaries and Checking How Many (Key, Value) Pairs Are Equal
What's the Bad Magic Number Error
Writing Unicode Text to a Text File
In Python, How to Convert All of the Items in a List to Floats
Append Multiple Values for One Key in a Dictionary
How to Jump to a Particular Line in a Huge Text File
Plot a Horizontal Line on a Given Plot
Elegant Python Code for Integer Partitioning
Getting the Index of the Returned Max or Min Item Using Max()/Min() on a List
Finding Local Maxima/Minima with Numpy in a 1D Numpy Array
Why Is Python 3.X's Super() Magic