html.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2013 com authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package com
  15. import (
  16. "html"
  17. "regexp"
  18. "strings"
  19. )
  20. // Html2JS converts []byte type of HTML content into JS format.
  21. func Html2JS(data []byte) []byte {
  22. s := string(data)
  23. s = strings.Replace(s, `\`, `\\`, -1)
  24. s = strings.Replace(s, "\n", `\n`, -1)
  25. s = strings.Replace(s, "\r", "", -1)
  26. s = strings.Replace(s, "\"", `\"`, -1)
  27. s = strings.Replace(s, "<table>", "&lt;table>", -1)
  28. return []byte(s)
  29. }
  30. // encode html chars to string
  31. func HtmlEncode(str string) string {
  32. return html.EscapeString(str)
  33. }
  34. // decode string to html chars
  35. func HtmlDecode(str string) string {
  36. return html.UnescapeString(str)
  37. }
  38. // strip tags in html string
  39. func StripTags(src string) string {
  40. //去除style,script,html tag
  41. re := regexp.MustCompile(`(?s)<(?:style|script)[^<>]*>.*?</(?:style|script)>|</?[a-z][a-z0-9]*[^<>]*>|<!--.*?-->`)
  42. src = re.ReplaceAllString(src, "")
  43. //trim all spaces(2+) into \n
  44. re = regexp.MustCompile(`\s{2,}`)
  45. src = re.ReplaceAllString(src, "\n")
  46. return strings.TrimSpace(src)
  47. }
  48. // change \n to <br/>
  49. func Nl2br(str string) string {
  50. return strings.Replace(str, "\n", "<br/>", -1)
  51. }