url2markdown
Version:
Convert all url/links to markdown
80 lines (62 loc) • 2.77 kB
JavaScript
var _ = require('lodash');
var url2markdown = module.exports;
/*
* Converts all links in the string to markdown
* www.xxx.com || http/https://www.xxx.com -> [http/s://www.xxx.com](http/s://www.xxx.com)
* Author : Shylesh Mohan - shylesh@eatsleepride.com - 2015 August
*/
url2markdown.convert = function (string) {
// This is an experiment.
// This specific function is implemented using one of the worst logic ever!
// How many people look at the code and cares a bit to start an issue or send a PR.
// Let's see.
// Oh and this method works perfectly and it's never gonna let you down & desert you.
var re = /(\b(http|https|ftp|Http|Https):\/\/|www[.]|Www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/)|[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
var pushToReplace = [];
var found_count = 0;
return _htmlChecker(string);
function _htmlChecker(str) {
try {
var matches = str.match(re);
if (!matches || matches.length <= 0) return str;
for (var i = 0; i < matches.length; i++) {
var index = str.indexOf(matches[i], 0);
var markup_check = _checkIfCoveredByMarkUp(str, matches[i], index);
if (markup_check === false) {
str = _coverWithMarkup(str, matches[i], index);
found_count++;
}
}
if (pushToReplace.length > 0) {
_.forEach(pushToReplace, function (markdown, key) {
str = str.replace("{{MARKUP_" + key + "}}", markdown);
})
}
} catch (e) {
console.log("REGEX ERROR : " + e);
return str;
}
return str;
}
function _coverWithMarkup(haystack, string, index) {
var appendProtocol = "";
if (string.indexOf("http://") != 0 && string.indexOf("https://") != 0) appendProtocol = "http://";
var replace_string = "[" + string + "]" + "(" + appendProtocol + string + ")";
pushToReplace.push(replace_string.toLowerCase());
haystack = haystack.replace(string, "{{MARKUP_" + found_count + "}}");
return haystack;
}
function _checkIfCoveredByMarkUp(haystack, needle, index) {
var startingPosition = index;
var endPosition = index + (needle.length - 1);
var wrapStart = startingPosition - 1;
var wrapEnd = endPosition + 1;
if (haystack[wrapStart] === '[' && haystack[wrapEnd] === ']' && haystack[wrapEnd + 1] === '(') {
return true;
}
if (haystack[wrapStart] === '(' && haystack[wrapEnd] === ')' && haystack[wrapStart - 1] === ']') {
return null;
}
return false;
}
};