#removeallspaces
#removewhitespaces
#string

Remove all spaces from string in Javascript

Anonymous

AnonymousOct 18, 2023

Remove all spaces from string in Javascript

In JavaScript, you can remove all white spaces from a string using several methods. Here are a few common methods:

Method 1: Using a regular expression with replace():

var textWithSpaces = "This is a text with spaces";
var textWithoutSpaces = textWithSpaces.replace(/\s/g, '');

console.log(textWithoutSpaces); // Output: "Thisisatextwithspaces"

Method 2: Using split() and join():

var originalString = "This is a sample string with spaces";
var stringWithoutSpaces = originalString.split(' ').join('');

console.log(stringWithoutSpaces);

Method 3: Using a loop to iterate through each character:

var originalString = "This is a sample string with spaces";
var stringWithoutSpaces = '';
for (var i = 0; i < originalString.length; i++) {
  if (originalString[i] !== ' ') {
    stringWithoutSpaces += originalString[i];
  }
}

console.log(stringWithoutSpaces);

Method 4: Using filter() and join() for ES6:

var stringWithSpaces = "This is a string with spaces";
var stringWithoutSpaces = stringWithSpaces.split('').filter(char => char !== ' ').join('');
console.log(stringWithoutSpaces); // Output: "Thisisastringwithspaces"

Happy Coding! ❤️