Eliminate all spaces from a string

$("#navMain" + $("#pathwaySecond").text().replace(/\s+/g, "")).addClass("active");

Here's a piece of my script. I need to append a class to an ID after accessing another ID's text content, but this text contains spaces. I attempted using TRIM() and REPLACE(), however, REPLACE() only removes the first occurrence of a space. How can I ensure all spaces are eliminated?

Hey there! :blush: It looks like you’re dealing with the challenge of removing all spaces from a text before using it to modify your element’s ID. No worries, there’s a handy way to do this using JavaScript’s replace() with a regular expression. Check out the code below:

$("#navMain" + $("#pathwaySecond").text().replace(/\s+/g, "")).addClass("active");

This uses the /\s+/g pattern, which matches any sequence of whitespace characters globally throughout the string, effectively removing all spaces you might encounter. I typically use this approach in my own projects when I need to clean up strings before further processing. If you run into any more snags or have questions, feel free to reach out!

Hi there!

To ensure all spaces are removed, apply the replace() method like this:

$("#navMain" + $("#pathwaySecond").text().replace(/\s+/g, "")).addClass("active");

This regex \s+/g removes all whitespace globally.