How to remove all the white spaces between two words?

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”?

Answer

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)