3

I'm using React (hooks) and in a component I have postcodes with a space in them in strings: eg "B72 1JL".

I need to remove the space in the middle of the postcodes so it is "B721JL" and also possibly any spaces before or after the postcode.

I've googled for ages and cannot find anything that will work. I know i probably need regex...but pretty confused!
Help appreciated.

2

1 Answer 1

20

Use String.prototype.replace() to change the space for an empty space.

const str = "B72 1JL";

// Replacing " " (space) to "" empty space
const res = str.replace(/ /g, '')
console.log(res); // BJ721JL
Sign up to request clarification or add additional context in comments.

2 Comments

That only replaces a single space. To replace all spaces, you would use str.replace(/ /g, '')
You are right, thanks! I will edit my answer!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.