# How to replace white space inside a string in JavaScript

> Learn how to remove or replace all the whitespace inside a string in JavaScript with a regular expression, using the whitespace metacharacter and the g flag.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2019-12-03 | Topics: [JavaScript](https://flaviocopes.com/tags/js/) | Canonical: https://flaviocopes.com/how-to-replace-whitespace-javascript/

Replacing all the white space inside a string is a very common need.

For example I last used this inside an API endpoint that received an image. I used the original image name to store it, but if it contained a space it was breaking my functionality (or other special chars, but let's focus on spaces)

So I researched the best way to do what I wanted. Turns out, a [regular expression](https://flaviocopes.com/javascript-regular-expressions/) was what I needed!

Here it is, in full

```js
const name = 'Hi my name is Flavio'
name.replace(/\s/g, '') //HimynameisFlavio
```

![How to replace white space inside a string in JavaScript](https://flaviocopes.com/images/how-to-replace-whitespace-javascript/replace-white-space-javascript.png)

The `\s` meta character in [JavaScript](https://flaviocopes.com/javascript/) regular expressions matches any whitespace character: spaces, tabs, newlines and Unicode spaces. And the `g` flag tells JavaScript to replace it multiple times. If you miss it, it will only replace the first occurrence of the white space.

Remember that the `name` value does not change. So you need to assign it to a new variable, if needed:

```js
const name = 'Hi my name is Flavio'
const nameCleaned = name.replace(/\s/g, '')
```
