Jump to content

User:Writ Keeper/Scripts/tableConverter.js

From 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.
//Code rewritten by kipod, copied from my talk page

$( function()
{
	function convertTable( table )
	{
		var str = '"' +
			$( "tr", table ).map( function( index, row ) {
				return ( $( "th,td", row )
					.map( function( index, cell ) {
						var clone = $( cell ).clone();
						clone.find( '*' ).filter( function() { return $( this ).css( 'display' ) == 'none'; } ).remove();
						return ( clone.text()
							.replace( /"/g, '""' )
							.replace( /\n/g, '\\n' ) );
					} )
					.toArray()
					.join( '","' ) );
			} )
			.toArray()
			.join( '"\n"' ) + '"';
		return mw.util.rawurlencode( str );
	}

	$( ".wikitable" ).each( function( index, table )
	{
		$( '<a>', { href: '#', download: 'table.csv' } )
			.text( 'Export as CSV' )
			.insertAfter( table )
			.click( function() { this.href = 'data:text/csv;charset=UTF-8,' + convertTable( table ); } );
	} );
} );