Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 732
Cecil Theodore Avatar asked Jul 08 '11 10:07

Cecil Theodore


People also ask

How do I remove blank spaces in a text file?

Press Shift + Alt then press the down button before "56". Then backspace . You will see the cursor becomes big and then you can remove the spaces all at once.


2 Answers

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

.replace(/ /g,'') 

The g character makes it a "global" match, meaning it repeats 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:

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

You can also use .replaceAll if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll, it must be global, so you just end up with extra typing:

.replaceAll(/\s/g,'') 
like image 180
Flimzy Avatar answered Oct 24 '22 02:10

Flimzy


.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, "") 
like image 37
Pantelis Avatar answered Oct 24 '22 04:10

Pantelis