- trim
- strip
1 Bash[ | ]
Bash
Copy
STR=" Hello, World "
echo "[$STR]" # [ Hello, World ]
TRIMMED=`echo $STR`
echo "[$TRIMMED]" # [Hello, World]
2 C++[ | ]

C++
Copy
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string s = " Hello, World ";
s.erase(s.begin(), find_if(s.begin(), s.end(), [](unsigned char ch) { return !isspace(ch); }));
s.erase(find_if(s.rbegin(), s.rend(), [](unsigned char ch) { return !isspace(ch); }).base(), s.end());
cout << '[' << s << ']'; // [Hello, World]
}
Loading
3 C#[ | ]
C#
Copy
string str = " HELLO ";
string trimmed = str.Trim();
4 Cmd[ | ]
bat
Copy
set str= Hello
echo [%str%]
for /f "tokens=* delims= " %a in ("%str%") do set str=%a
echo [%str%]
REM [ Hello ]
REM [Hello ]
5 Excel[ | ]
PHP
Copy
=TRIM(" HELLO ")
// returns 'HELLO'
6 Go[ | ]

Go
Copy
package main
import (
"fmt"
"strings"
)
func main() {
str := " HELLO ";
trimmed := strings.Trim(str," ");
fmt.Println("["+str+"]");
fmt.Println("["+trimmed+"]");
}
7 Java[ | ]
Java
Copy
String str = " HELLO ";
String trimmed = str.trim();
8 JavaScript[ | ]

JavaScript
Copy
function trim(str) {
return .replace(/^\s*/, '').replace(/\s*$/, '');
}
var str = " HELLO ";
var trimmed = trim(str);
JavaScript
Copy
String.prototype.trim=function(){return this.replace(/^\s*/,'').replace(/\s*$/,'');};
var str = " HELLO ";
var trimmed = str.trim();
9 jQuery[ | ]
JavaScript
Copy
var trimmed = $.trim(" HELLO ");
10 Objective-C[ | ]
Objective-C
Copy
NSString *str = @" HELLO ";
NSString *trimmed = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
11 PHP[ | ]
PHP
Copy
$trimmed = trim("\t hello \n"); // returns "hello"
12 Python[ | ]
Python
Copy
trimmed = "\t hello \n".strip() # returns "hello"
13 Perl[ | ]
Perl
Copy
my $trimmed=" hello ";
$trimmed =~ s/^\s+|\s+$//g;
Perl
Copy
use String::Util qw(trim);
$trimmed = trim(" hello ");
14 R[ | ]

R
Copy
s = " Hello, World "
print(s)
## [1] " Hello, World "
trimmed = gsub("^\\s+|\\s+$", "", s)
print(trimmed)
## [1] "Hello, World"
15 Ruby[ | ]
Ruby
Copy
trimmed = "\t hello \n".strip # returns "hello"
16 SQL[ | ]
16.1 MySQL[ | ]
sql
Copy
SELECT TRIM(' hello world ');
SELECT TRIM(" hello world ");
-- hello world
16.2 Oracle[ | ]
sql
Copy
LTRIM(RTRIM(" hello "));