User:GhostInTheMachine/SDlinkBuilder.js

Source: Wikipedia, the free encyclopedia.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
$.when( mw.loader.using( ['mediawiki.util'] ), $.ready )
.done( function() {
  mw.util.addPortletLink(
    'p-cactions',
    '#',
    'SDlinks',
    'ca-make-sd-links',
    'Build list of SDlinks'
  );
  $('#ca-make-sd-links').click(makeSDlinks);
});

function makeSDlinks(){

  var $links = $("#mw-content-text a[href^='/wiki/'].nonimage");
  var links = [];
  $links.each(function() {
    var href = this.href;

    if( href && href.substring(0,30) === 'https://en.wikipedia.org/wiki/' ) {
      href = href.substring(30);
      if( href.substring(0,5) !== 'Talk:'
        && href.substring(0,5) !== 'File:'
        && href.substring(0,5) !== 'Help:'
        && href.substring(0,5) !== 'User:'
        && href.substring(0,9) !== 'Category:'
        && href.substring(0,9) !== 'Template:'
        && href.substring(0,10) !== 'Wikipedia:'
        && href.substring(0,10) !== 'File_talk:'
        && href.substring(0,10) !== 'Help_talk:'
        && href.substring(0,10) !== 'User_talk:'
        && href.substring(0,14) !== 'Category_talk:'
        && href.substring(0,14) !== 'Template_talk:'
      ) {
        links.push(href);
      }
    }
  });

  links.sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
  });

  var prev = '';
  var page = '<pre>';

  $(links).each(function() {
    //  this is a string object
    thistext = this.trim().toLowerCase();
    if( thistext !== prev ) {
      prev = thistext;
      thistext = mw.Uri.decode(this).replace(/_/g, ' ');
      page += '* {{SDlink|' + thistext + '}}';
      page += "\n";
    }
  });
  page += '</pre>';

  $("#mw-content-text").html( page );

}