Skip to main content
1 of 8
brasofilo
  • 1k
  • 8
  • 22

Convert share links to markdown [title](url)

Replaces the original URL shown by the share link dialog, converting http://share-url to [question-title](http://share-url):

#Install script
  View source

Code:

// ==UserScript==
// @name        (SE) Markdown on Share links
// @description Changes the share links on Q&As to [question-title](http://post-link)
// @namespace   http://stackapps.com/users/10590/brasofilo
// @version     1.0
// @license MIT http://opensource.org/licenses/MIT
// @match       *://*.askubuntu.com/*
// @match       *://*.mathoverflow.net/*
// @match       *://*.serverfault.com/*
// @match       *://*.stackapps.com/*
// @match       *://*.stackexchange.com/*
// @match       *://*.stackoverflow.com/*
// @match       *://*.superuser.com/*
// @grant none
// ==/UserScript==

var start_up = function( $ ) {
    // Run only on individual posts
    if( ( StackExchange.options.routeName.indexOf('Questions/Show') === -1 ) ) 
        return;
    
    /**
     * Escapes brackets on string
     */
    var escapeString =function( str ) {
        return str.replace(/\[/g, "\\[").replace(/\]/g, "\\]")
    };
    
    /**
     * Removes meta content from title and escapes brackets
     * A title like "Burninate [tag-name] [closed]" will become "Burninate \[always-check-your-errors\]"
     */
    var cleanTitle = function( str ) {
        var look = [ ' [closed]', ' [duplicate]', ' [on hold]', ' [migrated]', ' [fechado]', ' [duplicado]', ' [suspensa]', ' [migrado]' ];
        for (var j=0; j<look.length; j++) {
            if (str.indexOf(look[j]) > -1 ) {
                var replace = str.replace(look[j], '');
                return escapeString(replace);
            }
        }
        return escapeString(str);
    };
    
    /**
     * Replaces the share URL by a markdown link
     */
    var changeShareLink = function( $this ) {
        $input = $this.find('.share-tip input:first');
        $url = $input.val();
        $title = $('#question-header h1 a').text();
        $title = cleanTitle($title);
        $output = '[' + $title + '](' + $url + ')';
        $input.val( $output ).select();
    };
    
    $(".post-menu a.short-link").on("click", function(t) {
        $this = $(this).parent();
        setTimeout( function(){ changeShareLink( $this ); }, 250 );   
    });
};

function with_jquery( f ) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.textContent = "(" + f.toString() + ")(jQuery)";
    document.body.appendChild(script);
};

with_jquery( start_up );
brasofilo
  • 1k
  • 8
  • 22