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 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 removes only the leading or left-hand side using the 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 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>
    <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