How to eliminate spaces from text using JavaScript

I’m working with a JavaScript application and need help with string manipulation. I have text data that contains unwanted spaces throughout, and I want to clean it up by removing all the whitespace characters.

For example, I need to transform something like “AB 25 XY 1234” into “AB25XY1234” - basically getting rid of every single space in the string.

What’s the best approach to accomplish this in JavaScript? I’ve been trying different methods but haven’t found the right solution yet. Any suggestions would be really helpful.

let messyText = "AB 25 XY 1234";
// Need to convert this to: "AB25XY1234"

Most people reach for regex or split/join methods, but that’s just scratching the surface.

messyText.replace(/\s/g, '') strips spaces instantly. But after years of dealing with messy data, I’ve learned you’re probably not cleaning just one string. You’ve got batches from APIs, user inputs, or databases.

Last month I processed thousands of product codes daily. Instead of writing cleanup scripts repeatedly, I built a Latenode workflow that handles all our string processing automatically.

You can set up triggers for incoming data, apply multiple transformations (not just space removal), and route clean results wherever needed. No more manual string manipulation every time new data arrives.

For your immediate need:

let cleanText = messyText.replace(/\s/g, '');

But if you’re scaling this or handling it regularly, automation beats writing the same cleanup code over and over.

The replace method with regex is the standard approach, but I’ve hit some gotchas that might save you debugging time. /\s/g works great for regular spaces, but it grabs tabs, newlines, and other whitespace too. Sometimes that’s what you want, sometimes it breaks formatting you need. If you only want to remove regular spaces and keep other whitespace, use messyText.replace(/ /g, ‘’) instead. Learned this the hard way processing CSV data - removing tabs destroyed the column structure. Watch out for non-breaking spaces (  in HTML) too. Regular space removal won’t catch those. For web scraped content, try messyText.replace(/[\s\u00A0]/g, ‘’) to handle both regular and non-breaking spaces. For your example though, basic replace(/\s/g, ‘’) should work fine.

To efficiently remove spaces from a string in JavaScript, you can utilize the replace() method with a regular expression. Here’s a concise solution:

let messyText = "AB 25 XY 1234";
let cleanText = messyText.replace(/\s+/g, '');
console.log(cleanText); // "AB25XY1234"

The /\s+/g regex matches all forms of whitespace, ensuring that any extra spaces are cleaned up seamlessly. This approach is reliable and performs well with larger datasets.