Skip to main content

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.