How to trim a string using JavaScript?

To remove spaces from a string using JavaScript, you can use the string.trim() method. The trim() method removes spaces from both ends of a given string without changing the original string. The characters to be removed include space, tab, page, and line terminators (' ', \t, \r, \n, etc). The method returns a new string without any leading or trailing whitespace. To remove spaces from a string, you can use the string.replace() method. Like the string.trim() method, the string.replace() method does not change the original string but returns a copy of the string with all occurrences of the searched value replaced with the new value (see example below). In this JavaScript Trim whitespace from the string example, we remove spaces using the string.trim() method. Click Execute to run the JavaScript Trim String online and see the result
Loading...