trim() method removes whitespace from both ends of a string. It returns a new copy of the string with whitespace removed.
const string = " Hello World! "; console.log(string.trim()); // "Hello World!"
trim() method does not take any parameters.
A new string with whitespace removed from both ends while leaving the original string unchanged.
If you want to remove whitespace either from the beginning or the end of a string, you can use the
const string = " Hello World! "; console.log(string.trimStart()); // "Hello World! " console.log(string.trimEnd()); // " Hello World!" console.log(string.trim()); // "Hello World!" console.log(string); // " Hello World! "
Alternatively, it's possible to use the regular expression to achieve the same result.
const string = " Hello World! "; console.log(string.replace(/^\s+|\s+$/g, "")); // "Hello World!"
If you're really curious about how this regex works, check out this Stack Overflow answer.
trim() method can come in handy when you need to remove unwanted whitespace from a string in user input or search queries.
I hope this article helped you understand how the
trim() method works. Regarding any questions or suggestions, feel free to leave a comment below. Thanks for reading! 🙂