JavaScript Trim a String

To trim whitespaces from both the ends of a string in JavaScript, call trim() method on this string.

Syntax

The syntax to call trim() method on this string str is

str.trim()

trim() returns a new string with whitespaces trimmed from the original string.

Examples

In the following example, we take a string str and trim the whitespaces at start and end of the string using trim().

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var str = '  hello world   ';
        var result = str.trim();

        var output = '';
        output += 'Original String : "' + str + '"';
        output += '\n\nTrimmed String  : "' + result + '"';
        document.getElementById('output').innerHTML = output;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to trim whitespaces from the edges of a string in JavaScript, using trim() method, with examples.