snippetjavascriptCritical
How to remove spaces from a string using JavaScript?
Viewed 0 times
howfromremovespacesusingstringjavascript
Problem
How to remove spaces in a string? For instance:
Input:
Output:
Input:
'/var/www/site/Brand new document.docx'Output:
'/var/www/site/Brandnewdocument.docx'Solution
This?
Example
Update: Based on this question, this:
is a better solution. It produces the same result, but it does it faster.
The Regex
A great explanation for
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.
str = str.replace(/\s/g, '');Example
var str = '/var/www/site/Brand new document.docx';
document.write( str.replace(/\s/g, '') );
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.
Code Snippets
str = str.replace(/\s/g, '');str = str.replace(/\s+/g, '');Context
Stack Overflow Q#5963182, score: 1790
Revisions (0)
No revisions yet.