replace() method with a regex that matches all two or more consecutive whitespace characters.
replace() method returns a new string with the matched values replaced without changing the original string.
replace() method accepts a value or a regular expression to search for in the string.
If you pass a value, only the first instance will be replaced. To replace all occurrences of a value, use a regular expression with the
g modifier set.
replace() method replaces all values that match the given regular expression with the new value and returns the new string.
Alternatively, you could use the
replaceAll() method to multiple spaces with a single space:
replaceAll() method was introduced in ES2021. It replaces all occurrences of the search string with the replacement text and returns a new string.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.