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 JavaScript Trim string function to remove leading and trailing whitespaces is


JavaScript trim Function Example

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

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

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

In the next line str4, deletes the trailing or Right-hand side of 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 this objects. If you observe the above screenshot, Trim function is delete the terminators like \t and \n

<!DOCTYPE html>
    <title> TRIMJavaScript </title>
    <h1> JavaScriptTRIM </h1>
    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 \>");
JavaScript TRIM Function