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. The syntax of the Trim string function to remove leading and trailing whitespaces is

String_Object.trim()

JavaScript trim Function Example

The following set of examples will help you understand how to use a trim function to remove whitespace characters or extra spaces from the original string.

In the beginning, we declared the String variable Str1 and assigned the corresponding value using the var str1 statement. The second line removes the white spaces from both the Left & Right sides of the Str1 variable.

var str3 remove only the leading or left-hand side using the Trim function. It deletes white spaces from the left-hand side.

In the next line, str4 deletes the trailing or Right-hand side of the string using the String Function. The following JavaScript statement removes white spaces from the right-hand side.

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

<!DOCTYPE html>
<html>
<head>
    <title>TRIM</title>
</head>
<body>
    <h1> JavaScriptTRIM</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