Skip to content

Commit

Permalink
Replace 4 strings.Replace with 1 strings.Replacer
Browse files Browse the repository at this point in the history
Consumes less memory, slightly faster.
  • Loading branch information
bep committed Feb 5, 2015
1 parent 5df8577 commit 2bee4a1
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 8 deletions.
13 changes: 5 additions & 8 deletions helpers/content.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,18 +69,16 @@ var blackfridayExtensionMap = map[string]int{
"autoHeaderIds": blackfriday.EXTENSION_AUTO_HEADER_IDS,
}

var stripHTMLReplacer = strings.NewReplacer("\n", " ", "</p>", "\n", "<br>", "\n", "<br />", "\n")

// StripHTML accepts a string, strips out all HTML tags and returns it.
func StripHTML(s string) string {
output := ""

// Shortcut strings with no tags in them
if !strings.ContainsAny(s, "<>") {
output = s
return s
} else {
s = strings.Replace(s, "\n", " ", -1)
s = strings.Replace(s, "</p>", "\n", -1)
s = strings.Replace(s, "<br>", "\n", -1)
s = strings.Replace(s, "<br />", "\n", -1) // <br /> is the xhtml line break tag
s = stripHTMLReplacer.Replace(s)

// Walk through the string removing all tags
b := new(bytes.Buffer)
Expand All @@ -97,9 +95,8 @@ func StripHTML(s string) string {
}
}
}
output = b.String()
return b.String()
}
return output
}

// StripEmptyNav strips out empty <nav> tags from content.
Expand Down
2 changes: 2 additions & 0 deletions helpers/content_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ func TestStripHTML(t *testing.T) {
{"<h1>strip h1 tag <h1>", "strip h1 tag "},
{"<p> strip p tag </p>", " strip p tag \n"},
{"</br> strip br<br>", " strip br\n"},
{"</br> strip br2<br />", " strip br2\n"},
{"This <strong>is</strong> a\nnewline", "This is a newline"},
}
for i, d := range data {
output := StripHTML(d.input)
Expand Down

0 comments on commit 2bee4a1

Please sign in to comment.