Skip to content
Fix Code Error

Remove ALL white spaces from text

March 13, 2021 by Code Error
Posted By: Anonymous
$("#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

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,'')
Answered By: Anonymous

Related Articles

  • in responsive menu it puts two links on the same line
  • What are the undocumented features and limitations of the…
  • Reference - What does this regex mean?
  • Improved way to get subsets of a list
  • How to make `` not expand when `` is hovered
  • Is it possible to apply CSS to half of a character?
  • How to properly do JSON API GET requests and assign output…
  • Active tab issue on page load HTML
  • regex match any single character (one character only)
  • How to use Regular Expressions (Regex) in Microsoft Excel…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

SQL multiple column ordering

Next Post:

How to represent multiple conditions in a shell if statement?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error