Use the replace() function with a regular expression to remove(trim) all whitespace from a 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:
Remove Whitespace Characters from Both Ends of a String
let str = ' JS trim ';
let result = str.trim();
console.log(result); // "JS trim"
The trim()
method removes whitespace characters such as spaces, tabs, and newlines from both the beginning and end of the string. If you only want to trim whitespace from the beginning or end, you can use trimStart()
or trimEnd()
respectively, but these are less commonly used compared to 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