github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/Unknwon/com/html.go (about)

     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  
    15  package com
    16  
    17  import (
    18  	"html"
    19  	"regexp"
    20  	"strings"
    21  )
    22  
    23  // Html2JS converts []byte type of HTML content into JS format.
    24  func Html2JS(data []byte) []byte {
    25  	s := string(data)
    26  	s = strings.Replace(s, `\`, `\\`, -1)
    27  	s = strings.Replace(s, "\n", `\n`, -1)
    28  	s = strings.Replace(s, "\r", "", -1)
    29  	s = strings.Replace(s, "\"", `\"`, -1)
    30  	s = strings.Replace(s, "<table>", "&lt;table>", -1)
    31  	return []byte(s)
    32  }
    33  
    34  // encode html chars to string
    35  func HtmlEncode(str string) string {
    36  	return html.EscapeString(str)
    37  }
    38  
    39  // decode string to html chars
    40  func HtmlDecode(str string) string {
    41  	return html.UnescapeString(str)
    42  }
    43  
    44  // strip tags in html string
    45  func StripTags(src string) string {
    46  	//去除style,script,html tag
    47  	re := regexp.MustCompile(`(?s)<(?:style|script)[^<>]*>.*?</(?:style|script)>|</?[a-z][a-z0-9]*[^<>]*>|<!--.*?-->`)
    48  	src = re.ReplaceAllString(src, "")
    49  
    50  	//trim all spaces(2+) into \n
    51  	re = regexp.MustCompile(`\s{2,}`)
    52  	src = re.ReplaceAllString(src, "\n")
    53  
    54  	return strings.TrimSpace(src)
    55  }
    56  
    57  // change \n to <br/>
    58  func Nl2br(str string) string {
    59  	return strings.Replace(str, "\n", "<br/>", -1)
    60  }