Skip to content

JavaScript trim Method | Remove space in characters string

  • by

The javaScript trim method is used in JavaScript, which removes the white spaces from both the ends of the given string. It’s not changed the original string. String trim() method not required any paraments.

Syntax

string.trim()

Examples JS trim method

We will see a different example of a trim() method.

1. JavaScript trim character

Remove space both sides or one side of Single character.

<!DOCTYPE html> 
<html> 
	<script> 

    var str = " 	EyeHunts      ";
	var st = str.trim();   
	document.write(st); 
  
</script> 

<body> 

</body> 
</html> 

It will remove one side space only if only leading or the trailing spaces are in the string str.

Output:

JavaScript trim Method

2. trimLeft() only remove the left side space

Use it when you want the left side trim characters in JavaScript.

<!DOCTYPE html> 
<html> 
	<script> 

    var str = " 	EyeHunts      ";
	var st = str.trimLeft();   
	alert(st); 
  
</script> 

<body> 

</body> 
</html> 

Output:

JS trimLeft remove the left side space

3. trimRight() only Remove Right side white space

Use it when wanting to remove extra spaces from the end of the string.

<!DOCTYPE html> 
<html> 
	<script> 

    var str = " 	EyeHunts      ";
	var st = str.trimRight();   
	alert(st); 
  
</script> 

<body> 

</body> 
</html> 

Output:

trim Remove Right side white space character

Q: How to Javascript remove spaces between words?

Answer: It’s very easy, you have to use replace() method. See the below code.

var str = "E H Y H U N T S";
str = str.replace(/ +/g, "");

Bonus:- Here is the link of other ways to remove white space in a string – JavaScript Remove whitespace of String

Do comment if you know about any other use of the trim method in JS or have any doubts.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading