Cecil Theodore Cecil Theodore - 1 month ago 9
Javascript Question

Remove ALL white spaces from text


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.

Thanks a bunch in advance, I know I am missing something small.

Answer

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 as well:

.replace(/\s/g,'')
Comments