;

How to Trim String in JavaScript


Tutorialsrack 27/02/2022 Jquery Javascript

In this article, you’ll learn how to trim strings in javascript. It is a good practice when using string values from form fields to remove the whitespace characters including spaces, tabs, etc. from the start and end of the strings, i.e. trim the string. 

To remove just the leading whitespace, you can use the trimStart() function. To remove the trailing whitespace, you can use the trimEnd() function. Or to remove all whitespace from the start and end of the strings, you can use the trim() function.

What is Whitespace

Before starting working with the actual trim functions, let us first know what special characters the trim functions are removing from strings. 

Here are some common whitespace characters from the list:

  • space
  • tab
  • no-break space
  • line terminator characters

Here are some examples to trim strings in javascript.

Example 1: Using trim() Function

This trim() function removes the whitespace from the start and end of the string.

console.log("   Hello World!   ".trim());      
//output ==> "Hello World!"

console.log("Hello World!  \n".trim());      
//output ==> "Hello World!"

console.log("Hello World!  \t".trim());      
//output ==> "Hello World!"

console.log("Hello World! \r".trim());      
//output ==> "Hello World!"

console.log("\t Hello World! \n".trim());      
//output ==> "Hello World!"

Example 2: Using trimStart() Function

This function removes the whitespaces from the start of the string.

console.log("   Hello World!   ".trimStart());      
//output ==> "Hello World!   "

console.log("\n  Hello World!  ".trimStart());      
//output ==> "Hello World!  "

console.log("\t  Hello World!  \t".trimStart());      
//output ==> "Hello World!   "

console.log("\r   Hello World! ".trimStart());      
//output ==> "Hello World! "

console.log("\t   Hello World!".trimStart());      
//output ==> "Hello World!"

Example 3: Using trimEnd() Function

This function removes the whitespaces from the start of the string.

console.log("   Hello World!   ".trimEnd());      
//output ==> "   Hello World!"

console.log("\n  Hello World!  ".trimEnd());      
//output ==> "\n  Hello World!"

console.log("\t  Hello World!  \t".trimEnd());      
//output ==> "\t  Hello World!"

console.log("\r   Hello World! \r".trimEnd());      
//output ==> "\r   Hello World!"

console.log("\t   Hello World!   ".trimEnd());      
//output ==> "\t   Hello World!"

I hope this article will help you to understand how to trim or remove whitespace from the strings in javascript

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags