2

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.

helen8297
  • 195
  • 1
  • 3
  • 10
  • 1
    Does this answer your question? [How to remove spaces from a string using JavaScript?](https://stackoverflow.com/questions/5963182/how-to-remove-spaces-from-a-string-using-javascript) – jasonandmonte May 10 '20 at 22:51
  • https://www.w3schools.com/jsref/jsref_trim_string.asp You can remove spaces with the .trim() method in javascript. – Xavier May 10 '20 at 23:11

1 Answers1

16

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
Claudio Busatto
  • 721
  • 7
  • 17