xxxxxxxxxx
// Removing spaces from a string using JavaScript
const str = "Hello, this is a test string.";
// Method 1: Using regular expressions
const removedSpaces1 = str.replace(/ /g, '');
console.log(removedSpaces1);
// Method 2: Using split() and join()
const removedSpaces2 = str.split(' ').join('');
console.log(removedSpaces2);
xxxxxxxxxx
const removeSpaces = str => str.replace(/\s/g, '');
// Example
removeSpaces('hel lo wor ld'); // 'helloworld'
xxxxxxxxxx
const originalString = "Hello World! This is a string with spaces.";
const stringWithoutSpaces = originalString.replace(/\s/g, "");
console.log(stringWithoutSpaces);
xxxxxxxxxx
var str = '/var/www/site/Brand new document.docx';
document.write( str.replace(/\s/g, '') );
xxxxxxxxxx
var str = '/var/www/site/Brand new document.docx';
document.write( str.replace(/\s/g, '') );
Run code snippetHide results
xxxxxxxxxx
str.replace(/\s+/g, '') //Replace str with variable name you have string saved too.