[JavaScript] Convert Text to Link in HTML

See demo first. (demo texts from the note in SN.1.11)

  菩提比丘長老英譯為「幸福者」(the Blessed One)。

View page source of this web page, and you will find 世尊譯詞的探討 is plain text in the page source. It is converted to a clickable link (<a> tag) via JavaScript.

The following is the source code of the demo.


var textToUrlMapping = {
  "世尊譯詞的探討": "http://agama.buddhason.org/book/bb/bb21.htm",

function TextToLink(elm) {
  elm.innerHTML = elm.innerHTML.replace(/〈(.+)〉/g, function(text, str1) {
    if (textToUrlMapping.hasOwnProperty(str1)) {
      return '〈<a href="'+ textToUrlMapping[str1] +
             '" target="_blank">' + str1 +
    return str1;

var t = document.querySelector(".line-block");
  • Use querySelector to select the element which contains the texts.
  • Call TextToLink function to convert the text in the element to link.
  • In TextToLink function, extract the text in 〈〉 via the pattern 〈(.+)〉.
  • Get the URL from text-to-url mapping, and create the link by the text and url.

Tested on: Chromium 63.0.3239.84 on Ubuntu 17.10 (64-bit)