Last active
September 15, 2018 21:09
-
-
Save bashkirtsevich/a06584926d7be2b9c627c5e7fe8a049d to your computer and use it in GitHub Desktop.
JS replace urls in markdown
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| plugins: [ | |
| function (hook, vm) { | |
| hook.beforeEach(function (html) { | |
| match_re = (src, re) => { | |
| result = new Array() | |
| while (1) { | |
| match = re.exec(src) | |
| if (match) { | |
| if (result.filter(item => item[0] === match[0]) == 0) | |
| result.push(match) | |
| } else | |
| break | |
| } | |
| return result | |
| } | |
| // patch all rel urls | |
| patch1 = html | |
| match_re(html, /\[([^\[\]]+)\]\((((?!http:\/\/|https:\/\/).+\.(?!md)[a-z]{2,})+)\)/g).forEach(match => { | |
| file_path = match.slice(-1)[0] | |
| old_url = match[0] | |
| new_url = old_url.replace( | |
| file_path, | |
| "https://gitlab.com/{{ root_path }}/blob/master" + file_path | |
| ) | |
| patch1 = patch1.replace(old_url, new_url) | |
| }) | |
| // add incons for links | |
| patch2 = patch1 | |
| match_re(patch1, /\[([^\[\]]+)\]\(([^)]+)\)/g).forEach(match => { | |
| link = match[0] | |
| if (match.slice(-1)[0].startsWith("/")) | |
| icon = "" | |
| else if (link.match("wiki")) | |
| icon = "<i class=\"fab fa-wikipedia-w\"></i>" | |
| else if (link.match("gitlab.com")) | |
| icon = "<i class=\"fab fa-gitlab\"></i>" | |
| else if (link.match("github.com")) | |
| icon = "<i class=\"fab fa-github\"></i>" | |
| else if (link.match("docs.google.com")) | |
| icon = "<i class=\"fas fa-file-alt\"></i>" | |
| else | |
| icon = "<i class=\"fas fa-link\"></i>" | |
| patch2 = patch2.replace(new RegExp(link.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'), "g"), `${icon} ${link}`) | |
| }) | |
| result = patch2 | |
| return result | |
| }) | |
| } | |
| ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment