The trim() method of the String class in JavaScript removes whitespace from both the beginning and end of a string.
The syntax of String.trim() method is:
trim()
This trim() method of String removes whitespace from both the beginning and end of the string.
String.trim() returns value of type String
.
In JavaScript, the trim()
method removes whitespace from both the beginning and end of a string.
For example,
str
with the value ' Hello World '
which has leading and trailing whitespace.trim()
method to remove the whitespace.newStr
.newStr
to the console using the console.log()
method.const str = ' Hello World ';
const newStr = str.trim();
console.log(newStr);
Hello World
In JavaScript, the trim()
method can be used to remove leading whitespace from a string.
For example,
str
with the value ' Hello'
which has leading whitespace.trim()
method to remove the whitespace.newStr
.newStr
to the console using the console.log()
method.const str = ' Hello';
const newStr = str.trim();
console.log(newStr);
Hello
In JavaScript, the trim()
method can be used to remove trailing whitespace from a string.
For example,
str
with the value 'Hello '
which has trailing whitespace.trim()
method to remove the whitespace.newStr
.newStr
to the console using the console.log()
method.const str = 'Hello ';
const newStr = str.trim();
console.log(newStr);
Hello
In this JavaScript tutorial, we learned about trim() method of String: the syntax and few working examples with output and detailed explanation for each example.