Remove ALL white spaces from text [duplicate]

Remove ALL white spaces from text [duplicate]

Possible Duplicate:
Replace all spaces in a string with ‘+’

$(“#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.


Solution 1:

You have to tell replace() to repeat the regex:

.replace(/ /g,'')

The g character means to repeat the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.

If you want to match all whitespace, and not just the literal space character, use \s instead:


Solution 2:

.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, "")