Skip to content

JavaScript trim whitespace | Example code

  • by

Use replace() function with a regular expression to remove(trim) all whitespace from string in JavaScript.

str.replace(/\s+/g, '');

if you are thinking of using the trim() method then you should know it trims the trailing spaces at the beginning and end.

str.trim()

JavaScript trim whitespace

Simple example code removes all whitespaces inside, end, and begging of a string in JavaScript

<!DOCTYPE html>
<html>
<body>
  <script>
    var str = "  Hello  world  ";
    var res = str.replace(/\s/g, "");

    console.log("Before:", str)
    console.log("After:", res)
  </script>

</body>
</html>

Output:

JavaScript trim whitespace

Remove Whitespace Characters from Both Ends of a String

let str = '  JS trim  ';
let result = str.trim();

console.log(result); // "JS trim"

Do comment if you have any doubts or suggestions on this JS trim topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *