JavaScript String trim()
Syntax & Examples
String.trim() method
The trim() method of the String class in JavaScript removes whitespace from both the beginning and end of a string.
Syntax of String.trim()
The syntax of String.trim() method is:
trim()This trim() method of String removes whitespace from both the beginning and end of the string.
Return Type
String.trim() returns value of type String.
✐ Examples
1 Using trim() method to remove leading and trailing whitespace
In JavaScript, the trim() method removes whitespace from both the beginning and end of a string.
For example,
- We define a string variable
strwith the value' Hello World 'which has leading and trailing whitespace. - We use the
trim()method to remove the whitespace. - The result is stored in the variable
newStr. - We log
newStrto the console using theconsole.log()method.
JavaScript Program
const str = ' Hello World ';
const newStr = str.trim();
console.log(newStr);Output
Hello World
2 Using trim() method on a string with only leading whitespace
In JavaScript, the trim() method can be used to remove leading whitespace from a string.
For example,
- We define a string variable
strwith the value' Hello'which has leading whitespace. - We use the
trim()method to remove the whitespace. - The result is stored in the variable
newStr. - We log
newStrto the console using theconsole.log()method.
JavaScript Program
const str = ' Hello';
const newStr = str.trim();
console.log(newStr);Output
Hello
3 Using trim() method on a string with only trailing whitespace
In JavaScript, the trim() method can be used to remove trailing whitespace from a string.
For example,
- We define a string variable
strwith the value'Hello 'which has trailing whitespace. - We use the
trim()method to remove the whitespace. - The result is stored in the variable
newStr. - We log
newStrto the console using theconsole.log()method.
JavaScript Program
const str = 'Hello ';
const newStr = str.trim();
console.log(newStr);Output
Hello
Summary
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.