How to replace or remove all spaces from a string in JavaScript?

If you want to replace or remove spaces from a string in JavaScript, keep reading!

There are times when you need to get rid of or change all the spaces in a string.

But you don’t know how? Well, this article will help you.

It is important to understand how to handle spaces in JavaScript can be useful.

In this article, we’ll show you how to remove or replace all spaces from a string in JavaScript, giving you clear explanations along with examples.

How to replace or remove all spaces in a string in JavaScript?

To remove or replace all spaces from a string in JavaScript, you can use regular expressions or built-in string methods and other methods below.

Let’s explore both approaches in detail.

Solution 1: Use Regular Expressions

Regular expressions are a powerful tool for finding and changing text in strings.

If you want to remove all the spaces in a string, you can use the replace() method along with a regular expression pattern.

Here’s an example that shows how to remove all the spaces in a string with nothing in JavaScript:

const str = "Hello, welcome to Itsourcecode! This is an example string with spaces.";
const result = str.replace(/\s/g, "");
console.log(result);

Output:

Hello,welcometoItsourcecode!Thisisaexamplestringwithspaces.

As you can see in this solution, we use the regular expression pattern /\s/g to find and remove all spaces characters (\s) from a string in JavaScript.

With the replace() method, each whitespace character that matches the pattern is replaced with nothing, effectively removing it from the string.

Solution 2: Use the split() and join() methods

JavaScript offers various built-in methods to modify strings. If you want to remove all spaces from a string, you can utilize the split() and join() methods together in JavaScript.

let str = "I t s o u r c e c o d e!";
let newStr = str.split(' ').join('');
console.log(newStr); 

This solution splits the original string into an array of substrings using the space character as the separator and then joins the substrings back together into a new string without any separator.

This effectively removes all spaces from the original string.

Output:

Itsourcecode!

Solution 3: Use for loop

To remove spaces from a string in JavaScript, you can use a for loop. This solution goes through each character in the string and creates a new string without spaces.

If a character is not a space, it is added to the new string. In the end, the new string will contain all the characters from the original string, but with no spaces.

let str = "I T S O U R C E C O D E !";
let newStr = "";
for (let i = 0; i < str.length; i++) {
    if (str[i] !== ' ') {
        newStr += str[i];
    }
}
console.log(newStr);

Output:

ITSOURCECODE!

Solution 4: Use the Array.prototype.filter() method

To replace all the spaces from a string in JavaScript, you can follow these steps:

  1. Convert the string into an array of characters using the Array.from() method.
  1. Use the Array.prototype.filter() method to create a new array that excludes spaces.
  1. Join the filtered array of characters into a string using the join() method.
let str = "I T S O U R C E C O D E !";
let newStr = Array.from(str).filter(char => char !== ' ').join('');
console.log(newStr);

This process will give you a new string without any spaces.

Output:

ITSOURCECODE!

Solution 5: Use replaceAll() method

The replaceAll() method is used with two arguments: a regular expression that matches all whitespace characters (/\s/g), and an empty string (”) to replace those spaces with.

By doing this, all spaces are effectively removed from the original string.

const str = " I T S O U R C E C O D E !";

const noWhitespace = str.replaceAll(/\s/g, '');
console.log(noWhitespace);

Output:

ITSOURCECODE!

Conclusion

In conclusion, this article provides multiple solutions to replace or remove all the spaces from a string in JavaScript.

It covers five solutions: using regular expressions, the split() and join() methods, a for loop, the Array.prototype.filter() method, and the replaceAll() method.

These approaches offer flexibility in handling spaces in strings and allow developers to choose the most suitable method for their specific needs.

We are hoping that this article provides you with enough information that helps you understand the JavaScript replace or remove all spaces.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Caren Bautista


Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel
 · View all posts by Caren Bautista →

Leave a Comment