How to trim string in JavaScript(3 ways)

JavaScript

In this post, we are going to learn how to trim strings in javascript. The string trimming means to remove the space generated by “space”, “tab”, “line-terminated character”,”carriage return charcater“,”form feed character“.JavaScript has three functions to achieve trimleft(), trimright() ,trim().

Ways to trim string in JavaScript


  • string.trim(): trim whitespace at start and end of string.
  • string.lefttrim() :It trims whitespace at beginning of string.
  • string.righttim() : It trims whitespace at end of string.

1. string.trim() to trim whitespace at start and end


The string.trim() method removes the whitespace character at the start and end of the string. It is a method of string object so always access with the object of string class.In this example we are removing line terminator (\n),tab(\t),carriage return(\r)

str1='\n Dev \n'.trim(); 
console.log(str1)

str2 = 'Enum \t'.trim(); 
console.log(str2)

str3 = 'Welcome \r'.trim(); 
console.log(str3)

Output

Dev
Enum
Welcome

trim whitespace at start and end of string

In this example, we are removing the leading and trailing whitespace from a given string.

const string = ' welcome ';


console.log(string.trim());



Output

welcome

2.trimstart()/trimleft() to trim whitespace at start of string


The string. trimStart() method used to remove leading whitespace at beginning of string.The trimleft() is alias of trimStart(). We can use either trimleft() or trimStart() method.It return a new string after removing the leading whitespace character.It is always recommend to use trimstart() in new ECMAScript code.

const str = '  welcome to devenum';

console.log(str.trimleft()); 
console.log(str.trimStart())

Output

welcome to devenum
welcome to devenum

3. trimEnd/trimright() to trim whitespace at end of string


The string.trimEnd() method used to remove trailing whitespace at end of string.The trimRight() is alias of trimEnd(). We can either use trimRight() or trimEnd() methods .

const str = 'welcome to devenum    ';

console.log(str.trimRight()); 
console.log(str.trimEnd())

Output

welcome to devenum
welcome to devenum

Summary

In this post we have learned how to trim string in JavaScript from beginning and end.The JavaScript string trim method remove whitespace created by charcater “space”, “tab”, “line-terminated character”,”carriage return charcater“,”form feed character