Remove spaces between words

Is there a better way to remove spaces between words than using a regular expression?

I would like to use a Params entry with printf to add to the end of a URL, while stripping out the white space between words. E.g. In Stock becomes InStock.

No, to remove all spaces you will need to scan the string for it.

The replaceRE function should be the fastest way to do so.

Hint, I would use backquotes to delimit the pattern so you don’t have to escape

This will remove all sequences of spaces and tabs with nothing.

replaceRE `(\s|\t)+` "" .Title
{{ printf "http://bla.com/%s" (replace .Params.foo " " "") }}

update: if you only want spaces you might also try replace .Title " " "" (maybe faster)

Worked like a charm! Thanks

Even though we cache the compiled regex, strings.Replace will be faster than strings.ReplaceRE.

{{ $c := "The Hunchback Of Notre Dame" }}
{{ range 100000 }}
  {{ $t := debug.Timer "Method A" }}
    {{ strings.Replace $c " " "" }}
  {{ $t.Stop }}
  {{ $t := debug.Timer "Method B" }}
    {{ strings.ReplaceRE `\s` "" $c }}
  {{ $t.Stop }}
  {{ $t := debug.Timer "Method C" }}
    {{ strings.ReplaceRE " " "" $c }}
  {{ $t.Stop }}
{{ end }}

If you need to replace any whitespace character (e.g., space, tab, newline) you’ll need to use Method B.

1 Like

per page, per site or per globally per regex?


always good to get a proof for an estimation :wink: thx

https://github.com/gohugoio/hugo/blob/master/tpl/strings/regexp.go#L102

ok. a struct definded in strings.go

var reCache = regexpCache{re: make(map[string]*regexp.Regexp)}

sounds quite global

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.