Introduction to JavaScript trim()
In JavaScript, the trim
method is a built-in method of the String prototype that is used to remove whitespace from the beginning and end of a string. This method takes no arguments and returns a new string with the whitespace removed.
In this article, we will discuss how to use the trim
method.
Using the trim()
method
Here is an example of how to use the trim
method to remove whitespace from a string:
let myString = " Welcome to the world of JavaScript ";
let trimmedString = myString.trim();
console.log(trimmedString);
Output
Welcome to the world of JavaScript
In this example, the trim
method is used to remove the whitespace from the beginning and end of the string Welcome to the world of JavaScript
. The trim
method is called on the string, and it returns a new string with the whitespace removed. The result is then logged to the console.
The trim
method is commonly used to clean up user input before it is processed or stored. For example, you might use the trim
method to remove leading and trailing whitespace from a user's name or address before saving it to a database. The trim
method can also be used to remove whitespace from the beginning and end of strings that you read from a file or other source.
Summary
The trim
method is a built-in method of the String prototype in JavaScript that is used to remove whitespace from the beginning and end of a string. This method is commonly used to clean up user input and to remove whitespace from strings that are read from a file or other source. The trim
method can also be used to remove whitespace from the middle of a string, although it is not designed specifically for that purpose.
References
String.prototype.trim() - JavaScript | MDN (mozilla.org)
Trim string in JavaScript - Stack Overflow