📜  mdn trim - Javascript (1)

📅  最后修改于: 2023-12-03 15:17:36.169000             🧑  作者: Mango

MDN Trim - Javascript

Introduction

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.

Syntax
string.trim()
Return Value

The trim() method returns the string with whitespace removed from both ends. If no whitespace is present, the original string is returned.

Example
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.

Availability

The trim() method is available in all modern browsers, as well as in Node.js.

Browser Compatibility

| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |--------|------|---------|-------------------|-------|--------| | 5 | 12 | 3.5 | 9 | 10.5 | 5 |

Conclusion

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.