📅  最后修改于: 2023-12-03 15:17:36.169000             🧑  作者: Mango
The trim()
method in JavaScript removes whitespace from both ends of a string. It's commonly used to clean up user input, especially when dealing with forms.
string.trim()
The trim()
method returns the string with whitespace removed from both ends. If no whitespace is present, the original string is returned.
const str = " Hello, World! ";
console.log(str.trim());
// Output: "Hello, World!"
In the example above, the str
variable contains whitespace before and after the desired string. By calling the trim()
method, the whitespace is removed and only "Hello, World!" is logged to the console.
The trim()
method is available in all modern browsers, as well as in Node.js.
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |--------|------|---------|-------------------|-------|--------| | 5 | 12 | 3.5 | 9 | 10.5 | 5 |
Using trim()
in JavaScript is a simple and effective way to remove whitespace from either end of a string. It's easy to use and available in all modern browsers.