You can use the replace() method with the regex in JavaScript to remove spaces from the string. Or use The trim() method to remove whitespace from both sides of a string.
.replace(/ /g,'')
The g character makes it a “global” match, repeating 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
Using split
and join
methods
Alternatively, you can use the split
method to split the string by spaces and then use the join
method to concatenate the array back into a string without spaces:
let str = "Hello World! How are you?";
let result = str.split(' ').join('');
console.log(result); // "HelloWorld!Howareyou?"
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