[javascript] Remove ALL white spaces from text

$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");

This is a snippet from my code. I want to add a class to an ID after getting another ID's text property. The problem with this, is the ID holding the text I need, contains gaps between the letters.

I would like the white spaces removed. I have tried TRIM()and REPLACE() but this only partially works. The REPLACE() only removes the 1st space.

This question is related to javascript jquery

The answer is


.replace(/\s+/, "") 

Will replace the first whitespace only, this includes spaces, tabs and new lines.

To replace all whitespace in the string you need to use global mode

.replace(/\s/g, "")

Use replace(/\s+/g,''),

for example:

const stripped = '    My String With A    Lot Whitespace  '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'

Using String.prototype.replace with regex, as mentioned in the other answers, is certainly the best solution.

But, just for fun, you can also remove all whitespaces from a text by using String.prototype.split and String.prototype.join:

_x000D_
_x000D_
const text = ' a b    c d e   f g   ';_x000D_
const newText = text.split(/\s/).join('');_x000D_
_x000D_
console.log(newText); // prints abcdefg
_x000D_
_x000D_
_x000D_


Regex for remove white space

\s+

_x000D_
_x000D_
var str = "Visit Microsoft!";
var res = str.replace(/\s+/g, "");
console.log(res);
_x000D_
_x000D_
_x000D_

or

[ ]+

_x000D_
_x000D_
var str = "Visit Microsoft!";
var res = str.replace(/[ ]+/g, "");
console.log(res);
_x000D_
_x000D_
_x000D_

Remove all white space at begin of string

^[ ]+

_x000D_
_x000D_
var str = "    Visit Microsoft!";
var res = str.replace(/^[ ]+/g, "");
console.log(res);
_x000D_
_x000D_
_x000D_

remove all white space at end of string

[ ]+$

_x000D_
_x000D_
var str = "Visit Microsoft!      ";
var res = str.replace(/[ ]+$/g, "");
console.log(res);
_x000D_
_x000D_
_x000D_


Now you can use "replaceAll":

console.log(' a b    c d e   f g   '.replaceAll(' ',''));

will print:

abcdefg

But not working in every possible browser:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll


Using .replace(/\s+/g,'') works fine;

Example:

this.slug = removeAccent(this.slug).replace(/\s+/g,'');