Ben Borgers / Posts /

How to remove double spaces in a string in JavaScript

January 30, 2021 by @benborgers

Here's how you can use regex in JavaScript to remove double spaces:

const string = 'Here is my sentence.  There are  double spaces.'

const newString = string.replace(/ {2,}/g, ' ')

This regex replaces any two or more spaces in a row with a single space.

A quick favor: was anything I wrote incorrect or misspelled, or do you still have questions? Please use this form to let me know or ask for help!