Logo

Programming-Idioms

  • JS
  • Haskell

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.

t= unwords $ words s

note that prefix/postfix spaces will be trimmed.
let t = s.replaceAll(/ {2,}/g, '')
let t = s.replaceAll(/\s{2,}/g, '')
let t = s.replace(/\s+/g, ' ');

This replaces any sequence of whitespaces with a single space.
(def t (clojure.string/replace s #"\s+" " "))

New implementation...