Too many spaces!!!

Nafis

Nafis / January 01, 2021

2 min read––– views

Stripping whitespaces from user input on the start and end of the string is standard procedure. We just use the Javascript's native .trim() method to remove dangling white spaces from the left or right or both:

const str = '     Hello World    '
const formatted = str.trim()

console.log(formatted) // => 'Hello World'

However, what if we want to get rid of extra spaces that are in between words in a sentence?

Example:
from 'nice       input' => 'nice input'?

Essentially, we want to remove extra whitespaces in the sentence (be it 2 or many), but we don't want to get rid of all the white spaces There's no JS native methods for this. 😢

Luckily for us, we can achieve our desired goal with trusty regex (along with the native .replace() method). This regex replaces one or more whitespaces with just one:

const str = 'Hello          World'
const formatted = str.replace(/\s\s+/g, ' ')

console.log(formatted) // => 'Hello World'

Voila! That works :)

Here's a handy formatter function (ready to go into production) 😋

const format = (str) => {
    if(!str || typeof str === 'string'){
        return ''
    }

    return str.replace(/\s\s+/g, ' ').trim()
}

Or, with Typescript (static type checking) 😁

const format = (str:string) :string => {
    return str?.replace(/\s\s+/g, ' ').trim()
}

Hope this snippet helps you (or maybe future me). Thanks for reading, enjoy! 🎉

# Comments and Feedback

Loading...

Subscribe to the boring interesting newsletter

If you enjoy learning new stuff, you should consider joining my newsletter 😇. Get emails from me about development 👩‍💻, tech 🤖, and other (un)opinionated matters 🤓. My newsletter includes early access to new/upcoming posts and sneak peek into special goodies. No spam ⛔, & you can unsubscribe at any time 🎉