Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #219 Replace multiple spaces with single space

Create the string t from the value of string s with each sequence of spaces replaced by a single space.

Explain if only the space characters will be replaced, or the other whitespaces as well: tabs, newlines.

import "regexp"
whitespaces := regexp.MustCompile(`\s+`)
t := whitespaces.ReplaceAllString(s, " ")

The whitespaces regexp can be reused.
(def t (clojure.string/replace s #"\s+" " "))

New implementation...
< >
programming-idioms.org