Javascript remove spaces method alternative

I had a custom javascript method that used regular expressions to replace all spaces in a given string, but just found an alternative that is worth knowing.

var str = 'this is some text';
var replaced = str.split(' ').join('+');

Will output “thisissometext”.

I have yet to check which is more performant, but at least it’s handy when doing javascript development and I don’t have my personal custom library around.After reading some more, performance results vary a lot depending on the browser used.

You can run some javascript comparisons of regex replacement vs split-join to see for yourself.

Leave a Reply

Your email address will not be published. Please enter your name, email and a comment.