Remove spaces from the string you can use replace() method with the regex in JavaScript. Or use The trim() method to remove whitespace from both sides of a string.
.replace(/ /g,'')
The g character makes it a “global” match, meaning it repeats the search through the entire string.
If you want to match all whitespace, and not just the literal space character, use \s
instead:
.replace(/\s/g,'')
Remove spaces from string JavaScript
Simple example code
<!DOCTYPE html>
<html>
<body>
<script>
const stripped = ' My String With A Lot Whitespace ';
var res = stripped.replace(/\s+/g, '')
console.log(stripped)
console.log(res)
</script>
</body>
</html>
Output:

You can also remove all whitespaces from a text by using String.prototype.split
and String.prototype.join
:
const text = ' a b c d e f g ';
const newText = text.split(/\s/).join('');
console.log(newText); // prints abcdefg
Do comment if you have any doubts or suggestions on this Js remove space topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version

Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.