![](/style/images/good.png)
![](/style/images/bad.png)
[JavaScript] Convert Text to Link in HTML
source link: http://siongui.github.io/2018/01/12/javascript-convert-text-to-link-in-html/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
[JavaScript] Convert Text to Link in HTML
January 12, 2018
See demo first. (demo texts from the note in SN.1.11)
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.
JavaScript:
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 + '</a>〉'; } return str1; }); } var t = document.querySelector(".line-block"); TextToLink(t);
- 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)
References:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK