JavaScript TRIM

The JavaScript TRIM function is a String function used to remove the empty spaces from both the Right-hand side and Left-hand side of a string. The syntax of the string Trim function in JavaScript Programming Language is

String_Object.trim()

JavaScript TRIM Function Example

The following set of examples will help you understand how to use a string trim function to trim extra spaces.

<!DOCTYPE html>
<html>
<head>
    <title> TRIM JavaScript </title>
</head>
<body>
    <h1> JavaScript TRIM </h1>
<script>
    var Str1 = "    Tutorial Gateway     ";
    var Str2 = Str1.trim();
    var Str3 = "    Tutorial Gateway".trim();
    var Str4 = "Tutorial Gateway     ".trim();
    var Str5 = " \t   Tutorial Gateway    \n ".trim();
 
    document.write(Str2 + "<br \>");
    document.write(Str3 + "<br \>");
    document.write(Str4 + "<br \>");
    document.write(Str5 + "<br \>");
</script>
</body>
</html>
JavaScript TRIM Function

First we declared the String variable Str1 and assigned corresponding value using following statement

var Str1 = "    Tutorial Gateway     ";

It removes the white spaces from both the Left & Right side of String variable Str1 using the trim function

var Str2 = Str1.trim();

Trimming only left-hand side of a string using JavaScript Trim function. It removes white spaces from the left-hand side

var Str3 = "    Tutorial Gateway".trim();

Trimming the Right-hand side of string using the Trim String Function. The following statement removes white spaces from the right-hand side

var Str4 = "Tutorial Gateway     ".trim();

Next, we used the line terminator along with string objects. If you observe the above screenshot, Trim function is trimming the terminators like \t and \n

var Str5 = " \t   Tutorial Gateway    \n ".trim();