JavaScript

Trim String

We can use the trim() method to remove whitespace from both ends of a string and return a new string, without modifying the original string.
If you need to trim a string only from the end, you can you the trimEnd() method.
If you need to trim a string only from the start, you can you the trimStart() method.

Here are the examples:

           
const string = "    Hello World!    ";

console.log(string.trim()); // 'Hello World!'

console.log(string.trimEnd()); // '    Hello World!'

console.log(string.trimStart()); // 'Hello World!    '           
    
Did you like this JavaScript code snippet? Share it with your friends: