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:
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:
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:
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