I need to remove all spaces from a string. For example:
Input: ‘/var/www/site/Brand new document.docx’
Output: ‘/var/www/site/Brandnewdocument.docx’
What’s the best way to JavaScript remove spaces from string in this case?
I need to remove all spaces from a string. For example:
Input: ‘/var/www/site/Brand new document.docx’
Output: ‘/var/www/site/Brandnewdocument.docx’
What’s the best way to JavaScript remove spaces from string in this case?
I’ve worked with string manipulation in JavaScript for over a years now, and the go-to method I always fall back on is using replace()
with a regular expression. It’s fast, clean, and super effective when you’re looking to javascript remove spaces from string entirely:
let str = '/var/www/site/Brand new document.docx';
let result = str.replace(/\s+/g, '');
console.log(result); // '/var/www/site/Brandnewdocument.docx'
\s+
matches all white spaces (spaces, tabs, newlines), and the g
flag makes sure every single one gets replaced. Simple and efficient.
Totally agree with @dimplesaini.230 —replace()
is my usual pick too. But when I first started learning JavaScript, I found using split()
and join()
a bit easier to understand. If you’re just getting started and want to javascript remove spaces from string in a more visual way:
let str = '/var/www/site/Brand new document.docx';
let result = str.split(' ').join('');
console.log(result); // '/var/www/site/Brandnewdocument.docx'
Here, you’re breaking the string at each space and then stitching it back together. It might not handle tabs or newlines like regex does, but it’s a great intro to understanding how strings work in JavaScript.
Great points by both of you guys, I’d like to add a slight twist to this. If your goal isn’t to javascript remove spaces from string entirely—but instead just clean up the beginning and end—you can start with trim()
and then apply replace()
as needed:
let str = ' /var/www/site/Brand new document.docx ';
let result = str.trim().replace(/\s+/g, '');
console.log(result); // '/var/www/site/Brandnewdocument.docx'
trim()
is perfect for getting rid of accidental spacing at the edges. Then, we fall back to regex for everything else. It’s a cleaner and more robust combo when you’re prepping data for further processing.