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
  • 547
  • 2
  • 5
  • 18

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
  • 547
  • 2
  • 5
  • 18
Spectric
  • 27,594
  • 6
  • 14
  • 39
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
  • 1,826
  • 1
  • 3
  • 23