For space-character removal use
"hello world".replace(/\s/g, "");
for all white space use the suggestion by Rocket in the comments below!
Answer from Henrik Andersson on Stack OverflowFor space-character removal use
"hello world".replace(/\s/g, "");
for all white space use the suggestion by Rocket in the comments below!
You can use
"Hello World ".replace(/\s+/g, '');
trim() only removes trailing spaces on the string (first and last on the chain).
In this case this regExp is faster because you can remove one or more spaces at the same time.
If you change the replacement empty string to '$', the difference becomes much clearer:
var string= ' Q W E R TY ';
console.log(string.replace(/\s/g, '

E$$
TY$
console.log(string.replace(/\s+/g, '#')); // #Q#W#E#R#TY#
Performance comparison - /\s+/g is faster. See here: http://jsperf.com/s-vs-s
Update
You can use too:
console.log(string.replaceAll(/\s/, '#')); // #Q#W#E#R#TY#
String.prototype.replaceAll()
Ways to remove spaces from a string using JavaScript
text - How to remove spaces from a string using JavaScript? - Stack Overflow
Remove whitespace Best Practice !?
javascript - Remove ALL white spaces from text - Stack Overflow
- To remove items from an array,
splicerequires you to specify how many to remove, in the second argument splicewill remove the item at the given index from the array, so on the next iteration, if you're iterating through indicies in ascending order, you may "skip" an item, due to its index having just been re-calculated
Easier to use .pop (remove from end) and .shift (remove from beginning).
const stringWithManyWhiteSpaces = ' I like ants... Remember us ';
function killLeftToRight(charArr) {
while (charArr[0] === ' ') {
charArr.shift();
}
}
function killRightToLeft(charArr) {
while (charArr[charArr.length - 1] === ' ') {
charArr.pop();
}
}
function myTrim(str){
const charArray = [...str];
killRightToLeft(charArray);
killLeftToRight(charArray);
console.log(charArray.join(''));
}
myTrim(stringWithManyWhiteSpaces);
your approach can be changed in different ways so it would work fine as mentioned in the previous answer, but if your target is to have your own implementation for trimming, what about implementing it in a simpler way?:
const stringWithManyWhiteSpaces = `
I like ants... Remember us
`;
function trimMe(stringToTrim) {
return stringToTrim.replace(/^[\s\n]+|[\s\n]+$/g, '')
}
console.log(trimMe(stringWithManyWhiteSpaces));
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.
SHORTEST and FASTEST: str.replace(/ /g, '');
Benchmark:
Here my results - (2018.07.13) MacOs High Sierra 10.13.3 on Chrome 67.0.3396 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):
SHORT strings
Short string similar to examples from OP question

The fastest solution on all browsers is / /g (regexp1a) - Chrome 17.7M (operation/sec), Safari 10.1M, Firefox 8.8M. The slowest for all browsers was split-join solution. Change to \s or add + or i to regexp slows down processing.
LONG strings
For string about ~3 milion character results are:
- regexp1a: Safari 50.14 ops/sec, Firefox 18.57, Chrome 8.95
- regexp2b: Safari 38.39, Firefox 19.45, Chrome 9.26
- split-join: Firefox 26.41, Safari 23.10, Chrome 7.98,
You can run it on your machine: https://jsperf.com/remove-string-spaces/1
You have to tell replace() to repeat the regex:
.replace(/ /g,'')
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.
If you want to match all whitespace, and not just the literal space character, use \s instead:
.replace(/\s/g,'')
You can also use .replaceAll if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll, it must be global, so you just end up with extra typing:
.replaceAll(/\s/g,'')
.replace(/\s+/, "")
Will replace the first whitespace only, this includes spaces, tabs and new lines.
To replace all whitespace in the string you need to use global mode
.replace(/\s/g, "")