Convert Text to HTML Link in Go


Convert some specific plain texts to clickable links in HTML documents via Go/GopherJS. This is actually the Go/GopherJS translation of my previous post [JavaScript] Convert Text to Link in HTML [1]. Please read my previous post and see the demo first. Here I only show the Go code of the implementation. The HTML code is the same as that in my previous post. The full code example of this post is on my GitHub.

package main

import (
      . "github.com/siongui/godom"
      "regexp"
)

var textUrl = map[string]string{
      "世尊譯詞的探討": "http://agama.buddhason.org/book/bb/bb21.htm",
}

var text = regexp.MustCompile(`〈.+〉`)

func TextToLink(elm *Object) {
      h := text.ReplaceAllStringFunc(elm.InnerHTML(), func(match string) string {
              key := match[3 : len(match)-3]
              url, ok := textUrl[key]
              if ok {
                      return `〈<a href="` + url +
                              `" target="_blank">` + key + `</a>〉`
              }
              return match
      })
      elm.SetInnerHTML(h)
}

func main() {
      b := Document.QuerySelector(".line-block")
      TextToLink(b)
}

The above code use godom package to make the code more readable.


References:

[1][JavaScript] Convert Text to Link in HTML