1

I have an input field on which the user types the city name, but what if the user types the city like this:

"New    York     "
"  New York           "

I used the trim function but that did not work, any suggestion?

const city = "New         York     ";

console.log(city.trim());

How can I remove all the white spaces so I can save the city in the state as "New York"?

Andres
  • 731
  • 2
  • 10
  • 22

2 Answers2

1

You can also use replace to replace all consecutive space characters with one space:

const str = "New    York     "
"  New York           "

const res = str.replace(/\s+/gm, " ").trim()

console.log(res)

Alternatively, you can split the string by a space, filter out the empty items, then join back by a space:

const str = "New    York     "
"  New York           "

const res = str.split(" ").filter(e=>e).join(" ")

console.log(res)
Andres
  • 731
  • 2
  • 10
  • 22
Spectric
  • 30,714
  • 6
  • 20
  • 43
1

Combine the string.replace() method and the RegEx and replace it with a single string. Notice the starting and ending spaces will be kept and stripped down to a single space. Trim any surrounding spaces from the string using JavaScript’s string.trim() method

const city = "    New         York     ";

console.log(city.replace(/\s+/g, ' ').trim());
Rukshan Jayasekara
  • 1,945
  • 1
  • 6
  • 26