Logo

Programming-Idioms

History of Idiom 219 > diff from v1 to v2

Edit summary for version 2 by programming-idioms.org:
New Go implementation by user [programming-idioms.org]

Version 1

2020-02-28, 08:57:20

Version 2

2020-02-28, 09:04:31

Idiom #219 Replace multiple spaces with single space

Create 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.

Idiom #219 Replace multiple spaces with single space

Create 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.

Extra Keywords
collapse repeated
Extra Keywords
collapse repeated
Imports
import "regexp"
Code
whitespaces := regexp.MustCompile(`\s+`)
t := whitespaces.ReplaceAllString(s, " ")
Comments bubble
The whitespaces regexp can be reused.
Doc URL
https://golang.org/pkg/regexp/#Regexp.ReplaceAllString
Origin
https://yourbasic.org/golang/remove-duplicate-whitespace/
Demo URL
https://play.golang.org/p/0mVNDeTSgyt