Action

TAD-MD-Link Unlinked β

Posted by sylumer, Last update over 3 years ago - Unlisted

BETA VERSION

Convert unlinked URLs to Markdown linked URLs. The URL is replaced by a Markdown link using the URL’s page title as the link text. This action will leave HTML source URLs and existing linked URLs unchanged.

Steps

  • includeAction

    name
    TAD
  • script

    //Initialise
    let objHTTP = HTTP.create();
    let strContent = draft.content;
    let strURLPattern = new RegExp(".{0,2}(?:(?:https?)://)(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))(?::\\d{2,5})?(?:[/?#]\\S*)?", "ig")
    
    //Find URL matches
    let astrMatches = strContent.match(strURLPattern);
    
    //Remove duplicates so we only have to retrieve page titles once
    astrMatches = [...new Set(astrMatches)];
    
    //For each match analyse it and replace it with a full Markdown link if necessary
    //Ignore existing Markdown links and HTML URL sources (e.g. HTML links and images also valid in Markdown)
    //Continue to cater for URLs in parentheses
    astrMatches.forEach(function(strMatch)
    {
    	//Just to ensure we have not picked up any rogue whitespace in the pattern match
    	strMatchTrimmed = strMatch.trim();
    
    	//Get the first two characters and the URL
    	let strStart = strMatchTrimmed.substring(0,2);
    	let strURL = strMatchTrimmed.substring(2);
    
    	//A bit more Reg Ex to ensure we account (primarily) for trailing characters like some type of bracket
    	//In a general sense, URLs should be starting with a non-symbol and ending with one.
    	strURL = strURL.match(/([a-zA-Z0-9]).*([a-zA-Z0-9])/)[0];
    
    	//If the URL happens to be right at the start of the string, we'll be stripping off the start of the URL.
    	//So we'll add some extra validation here to check the URL and add the two characters back if necessary.
    	if(!objHTTP.TA_isValidURL(strURL))
    	{
    		strStart = "";
    		//Let's reapply that Regular Expression macth
    		strURL = strMatchTrimmed.match(/([a-zA-Z0-9]).*([a-zA-Z0-9])/)[0];
    	}
    
    	//Existing Markdown and HTML links should be ignored
    	if(strStart == "](") console.log("IGNORE: Matched an existing Markdown link | " + strMatchTrimmed);
    	else if (strStart == '="') console.log("IGNORE: Matched an HTML link | " + strMatchTrimmed);
    	//Other links are fair game, replace the content
    	else strContent = strContent.replaceAll(strMatchTrimmed, strStart + objHTTP.TA_mdTitleLinkFromURL(strURL));
    });
    
    //Update the
    draft.content = strContent;
    draft.update();
    editor.activate();

Options

  • After Success Default
    Notification Error
    Log Level Error
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.