Remove whitespaces inside a string in javascript
Probably because you forgot to implement the solution in the accepted answer. That's the code that makes trim()
work.
update
This answer only applies to older browsers. Newer browsers apparently support trim()
natively.
For 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, '$')); // $$Q$$W$E$$$R$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