How to Remove Whitespace Characters from a String in JavaScript

White space is a term used in computing to describe any character that occupies space on a screen such as space, newline, or tab. In many programming languages, white space is considered to be insignificant and can be used to format code for readability.

There are various ways to remove whitespace characters from a string in JavaScript. The trim() method is the most common way to remove whitespace characters from a string. This method removes both leading and trailing whitespace characters from a string. This does not change any input characters, but only removes whitespace from both sides of it and returns a new copy without these extra bits around your data.

Another method is to use the replace() method, which returns a new string with some or all matches of the pattern replaced by a replacement. The pattern can be a string or a RegExp.

var str = '         JavaScript strings are used to store and manipulate text. They are one of the most important data types in JavaScript. In fact, almost all JavaScript programs use strings in one way or another.     ';
//remove both leading and trailing whitespace characters
var newStr = str.trim();

//remove all white spaces
var noBlankSpaceText = str.replaceAll(' ', '');
var noBlankSpaceText2 = str.replace(/ /g,'');
var noBlankSpaceText3 = str.replaceAll(/\s/g,'');
var noBlankSpaceText4 = str.replace(/\s+/, '') ;

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.