javascript remove all spaces – How to remove spaces from a string using JavaScript ?

javascript remove all spaces – The whitespace characters are space, tab, no-break space, etc. The trim() method removes whitespace from both ends of a string.

javascript remove all spaces

If you want to remove all whitespace from a string and not just the literal space character, use \s instead. You can remove the whitespace in a string by using a string.replace(/\s/g, “”) regular expression.

2 ways to remove whitespace from a string

  • Regular expression
  • Split() + Join()

Remove ALL white spaces from text
using replace() to repeat the regex:

.replace(/ /g,'')

Don’t Miss : Remove space between string in jQuery

Read Also:  Vue js Toggle switch Update DB field using Ajax

Remove all whitespace from a string in JavaScript

Example 1: Using Split() with Join() method

const member_comments = '   HowDoYouDo Friends   ';
console.log(member_comments.split(' ').join(''));

Using Regular Expression

Example : 1

const member_comments = '   HowDoYouDo Friends   ';
console.log(member_comments.replace(/ /g,''));

Example : 2

const member_comments = '   HowDoYouDo Friends   ';
console.log(member_comments.replace(/\s/g,''));

remove all spaces from string javascript

var member_comments = "       HowDoYouDo Friends!        ";
alert(member_comments.trim());

javascript remove all spaces

var string = "Javascript is fun";
var newString = string.replace(" ", "_");
console.log(newString); // Javascript_is_fun

I hope you get an idea about javascript remove all spaces.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.