Use the trim(), trimStart(), and trimEnd() to Handle White Spaces

The trim() method gets rid of white spaces at both ends of the string. The trimStart() gets rid of white spaces at the start of the string. And trimEnd() removes white spaces at the end of the string.
These three methods are useful when we need to clean up user inputs or remove leading/trailing whitespace from strings.

Some Example are added below

const greet = '   Hello world!   ';
console.log(greet.trim());
Output:-Hello world!

const greet2 = '   Hello world!   ';
console.log(greet2.trimStart());
Output: 'Hello, world!   '

const text = '   Hello world!   ';
console.log(text.trimEnd());
Output: '   Hello world!'

const input = '   ';
if (input.trim() === '') {
  console.log('The input is empty but has whitespace characters.');
} else {
  console.log('The input contains non-whitespace characters.');
}
Output: The input is empty but has whitespace characters.

Leave a comment

Your email address will not be published. Required fields are marked *