Andres
Andres

Reputation: 795

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

Upvotes: 1

Views: 126

Answers (2)

Spectric
Spectric

Reputation: 32000

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)

Upvotes: 1

Rukshan Jayasekara
Rukshan Jayasekara

Reputation: 1985

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());

Upvotes: 1

Related Questions