javascript string trim() method

JavaScript String trim() method

In this article, we will see how the Javascript String trim() method works. The trim() is one of the built-in functions of a string. This function is used to remove the white space from both sides of a string.

Javascript string trim() method Syntax

string.trim()

Note that trim() function does not take any argument. It is only used to remove the spaces from starting and end of the string.

The trim() method returns the existing string with no white space.

trim() method examples in JavaScript

Below are the different types of examples of the javaScript trim() function.

Example 1:

<html>
    <head>
        <title>Trim function</title>
    </head>
    <body>
        <h1>Javascript trim() function</h1>
        <pre><p id="a"></p></pre>
        <pre><p id="b"></p></pre>    
        <script>
            var a = "    developerhelps  "
            var b = a.trim();
            document.getElementById("a").innerHTML=a;
            document.getElementById("b").innerHTML=b;
        </script>
    </body>

</html>

Output :

Javascript string trim() funtion

What is the use of <pre> tag in HTML

We use the <pre> tag here because, by default, HTML can remove all the extra white spaces from our code. However, to see the code as you type it, we use the <pre> tag here. 

You can learn more about <pre> tag from here HTML <pre> tag.

Example 2:

<html>
    <head>
        <title>Trim function</title>
    </head>
    <body>
        <h1>Javascript trim() function</h1>
        <pre><p id="a"></p></pre>
        <pre><p id="b"></p></pre>    
        <script>
            var a = "developerhelps   "
            var b = a.trim();
            document.getElementById("a").innerHTML=a;
            document.getElementById("b").innerHTML=b;
        </script>
    </body>

</html>

Output :

Here, we use the white space only at the right end, and it gives output by removing the white space from the right end.
In the output, you can see that I select both the string i.e. a string with white space and a string without white space.