This?

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

Example

var str = '/var/www/site/Brand new document.docx';

document.write( str.replace(/\s/g, '') );
Run code snippetEdit code snippet Hide Results Copy to answer Expand


Update: Based on this question, this:

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

is a better solution. It produces the same result, but it does it faster.

The Regex

\s is the regex for "whitespace", and g is the "global" flag, meaning match ALL \s (whitespaces).

A great explanation for + can be found here.

As a side note, you could replace the content between the single quotes to anything you want, so you can replace whitespace with any other string.

Answer from Šime Vidas on Stack Overflow
🌐
Reddit
reddit.com › r/learnjavascript › ways to remove spaces from a string using javascript
r/learnjavascript on Reddit: Ways to remove spaces from a string using JavaScript
January 11, 2023 - Progress: 100% replaceAll: 902 907 ops/s, ±1.30% | fastest replace: 811 102 ops/s, ±0.42% | 10.17% slower split-join: 519 097 ops/s, ±1.99% | slowest, 42.51% slower spread-filter-join: 624 614 ops/s, ±0.41% | 30.82% slower Finished 4 cases! Fastest: replaceAll Slowest: split-join Running "Remove spaces (1000 characters string)" suite...
Discussions

javascript - Remove ALL white spaces from text - Stack Overflow
The REPLACE() only removes the 1st space. ... Save this answer. ... Show activity on this post. ... The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here. More on stackoverflow.com
🌐 stackoverflow.com
Remove whitespace Best Practice !?
hi everyone if you could rate my solution for that challenge, could you consider it Best Practice or Less or More (Average) or Newbie?? here my solution: let hello = " Hello, World! "; let wsRegex = /\s/g; // Chan… More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
5
0
May 13, 2019
How to remove spaces from String?
I want to combine two expressions to create a bucket in aws. The bucket name cannot have any spaces. How would I remove spaces from the strings? ex. Bucket Name: {{ $(‘Merge’).item.json.Client }}-{{ $(‘Merge’).item.json[‘Title of Project’] }} | OUTPUT would be: New York-Marketing ... More on community.n8n.io
🌐 community.n8n.io
1
0
June 27, 2025
removing all non-letter characters from a string? ((using regex))
This is very simple with regex. You just need to replace non-words (/\W/ig). So: var string = "lakjsdlkasjdlsaj@£$%^&*klajdlaskjds"; string.replace(/\W/ig, ""); --> "lakjsdlkasjdlsajklajdlaskjds" \w == words, \W == non words. You don't need a loop here as we're using /g which stands for global, so we replace every instance. And just incase I'm using /i as well which ignores the case. As it's regex you can just do /ig and the selectors will stack to ignore case and global. My favorite regex visualiser lives here: https://jex.im/regulex/#!embed=false&flags=ig&re=%5CW More on reddit.com
🌐 r/learnjavascript
10
4
September 28, 2015
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › trim
String.prototype.trim() - JavaScript | MDN
The trim() method of String values removes whitespace from both ends of this string and returns a new string, without modifying the original string.
🌐
W3Schools
w3schools.com › jsref › jsref_trim_string.asp
JavaScript String trim() Method
"; let result = text.trim(); Try ... = text.replace(/^\s+|\s+$/gm,''); Try it Yourself » · The trim() method removes whitespace from both sides of a string....
🌐
Medium
tariibaba.medium.com › javascript-remove-all-spaces-from-string-75f942ef2fbe
How to Remove All Spaces from a String in JavaScript | Medium
June 22, 2022 - For example, str.replaceAll(' ', '') removes all the spaces from str. const str = 'A B C'; const allSpacesRemoved = str.replaceAll(' ', '');console.log(allSpacesRemoved); // ABC · The String replaceAll() method returns a new string with all ...
🌐
DEV Community
dev.to › natclark › removing-whitespace-from-strings-in-javascript-4k32
Removing Whitespace From Strings in JavaScript - DEV Community
September 7, 2021 - With a bit of help from JavaScript's built-in RegEx features, this one-liner will remove all the whitespace from a given string: const string = `This is an example string.`; string.replace(/\s/g, ``); If you just want to remove the space character ...
Find elsewhere
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Remove whitespace Best Practice !? - Curriculum Help - The freeCodeCamp Forum
May 13, 2019 - hi everyone if you could rate my solution for that challenge, could you consider it Best Practice or Less or More (Average) or Newbie?? here my solution: let hello = " Hello, World! "; let wsRegex = /\s/g; // Change this line let result = hello.replace(wsRegex, "").replace(/,/g, ", "); // Change this
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-remove-spaces-from-a-string-using-javascript
How to Remove Spaces From a String using JavaScript? - GeeksforGeeks
The _.trim() method method removes leading and trailing whitespace from a string. ... JavaScript string.replace() method is used to replace a substring. With Regular expressions pattern we can find all spaces (/\s/g) and globally replace all ...
Published   July 12, 2025
🌐
Sololearn
sololearn.com › en › Discuss › 2734075 › how-to-remove-all-whitespaces-and-line-breaks-in-js-
How to remove all whitespaces and line breaks in js ?
March 23, 2021 - sl_scroll_/de/Discuss/359554/salam-les-amis-jai-un-probleme-en-javascript-est-ce-que-vous-pouvez-me-donnez-des-sites-ou-des-cours-pour-b1-dcouvrir-ce-languPending
🌐
ReqBin
reqbin.com › code › javascript › zcdulg8f › javascript-trim-string-example
How to trim a string using JavaScript?
To remove spaces from a string using JavaScript, you can use the string.trim() method. The trim() method removes spaces from both ends of a given string without changing the original string.
🌐
Lpsftt
lpsftt.works › ⇴ › ☷ › 꾳
Remove whitespaces from string JavaScript - lpsftt.works
lpsftt.works · Log In Sign Up · Germanwings-Absturz Schulklasse. Lovelton hotel restaurant · Perhiasan penuntut ilmu PDF. Wn araguari login · スギ薬局 サポーター 手首 · ⭖ ⭬ 暄 뚁 · Comments · Contact Us · Log In · ご⬻Ζ⇈
🌐
W3Schools
w3schools.com › js › js_string_methods.asp
JavaScript String Methods
Slice out a portion of a string from position 7 to position 13: let text = "Apple, Banana, Kiwi"; let part = text.slice(7, 13); Try it Yourself » · JavaScript counts positions from zero.
🌐
DEV Community
dev.to › ajaymarathe › create-js-function-to-remove-spaces-from-giving-string-26le
Create JS function to remove spaces from giving string. ( Using core js and not in-built trim function.) - DEV Community
August 15, 2024 - In other words, if you pass a sentence with spaces into this function, it will return the same sentence but with all the spaces removed. Splitting the String: The function starts by taking the input string (e.g., "Hello world nice world") and splits it into an array of individual characters. For example, "Hello world" becomes ['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']... Filtering Out Spaces: The function then goes through each character in the array. If the character is not a space (' '), it adds it to a new array called trimedStr.
🌐
CSS-Tricks
css-tricks.com › snippets › javascript › strip-whitespace-from-string
Strip Whitespace From String | CSS-Tricks
September 2, 2014 - Whitespace, meaning tabs and spaces. var str = " a b c d e f g "; var newStr = str.trim(); // "a b c d e f g" That method is ES 5, so just in case you could polyfill it (IE 8 and down): if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); }; } ... See the Pen Remove Whitespace from Strings by Chris Coyier (@chriscoyier) on CodePen.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › trimStart
String.prototype.trimStart() - JavaScript | MDN
July 10, 2025 - The trimStart() method of String values removes whitespace from the beginning of this string and returns a new string, without modifying the original string. trimLeft() is an alias of this method. const greeting = " Hello world! "; console.log(greeting); // Expected output: " Hello world!
🌐
n8n
community.n8n.io › questions
How to remove spaces from String? - Questions - n8n Community
June 27, 2025 - I want to combine two expressions to create a bucket in aws. The bucket name cannot have any spaces. How would I remove spaces from the strings? ex. Bucket Name: {{ $(‘Merge’).item.json.Client }}-{{ $(‘Merge’).item.json[‘Title of Project’] }} | OUTPUT would be: New York-Marketing ...
🌐
Text-Utils
text-utils.com › remove special characters
Remove Special Characters - Online Regex Tools | Text-Utils.com
September 6, 2025 - Keep alphanumeric only: Remove all non-alphanumeric characters from the text. Keep numeric & spaces only: Remove all non-numeric & non-space characters from the text.
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › string › check, compact or remove whitespaces
Check, compact or remove whitespaces in a JavaScript string - 30 seconds of code
January 27, 2024 - Similar to the previous example, you can use String.prototype.replace() with a regular expression to replace all occurrences of 2 or more whitespace characters with a single space. You can use the {2,} quantifier to match 2 or more whitespace characters and, again, the global flag (g) to match all occurrences. const compactWhitespace = str => str.replace(/\s{2,}/g, ' '); compactWhitespace('Lorem Ipsum'); // 'Lorem Ipsum' compactWhitespace('Lorem \n Ipsum'); // 'Lorem Ipsum' ... Learn how to use regular expressions to replace the last occurrence of a pattern in a JavaScript string. ... Learn how to remove accents from a string in JavaScript, quickly and efficiently.