Action

Sort CSV String

Posted by @sylumer, Last update over 5 years ago - Unlisted

Steps

  • script

    //Set to true to wrap (delimit) all CSV entries in double quotes
    //Set to false to not do this
    bDoubleQuotes = true;
  • script

    // Source = http://www.greywyvern.com/?post=258
    String.prototype.splitCSV = function(sep)
    {
    	for (var foo = this.split(sep = sep || ","), x = foo.length - 1, tl; x >= 0; x--)
    	{
    		if (foo[x].replace(/"\s+$/, '"').charAt(foo[x].length - 1) == '"')
    		{
    			if ((tl = foo[x].replace(/^\s+"/, '"')).length > 1 && tl.charAt(0) == '"')
    			{
    				foo[x] = foo[x].replace(/^\s*"|"\s*$/g, '').replace(/""/g, '"');
    			}
    			else if (x)
    			{
    				foo.splice(x - 1, 2, [foo[x - 1], foo[x]].join(sep));
    			}
    			else foo = foo.shift().split(sep).concat(foo);
    		}
    		else foo[x].replace(/""/g, '"');
    	}
    	return foo;
    };
    
    // Sort a CSV string and optionally wrap all content in double quotes
    // If there's any chance your content contains non-separator comms, you must set this to true
    function sortCSV(p_strCSV, p_bIncludeDoubleQuotes)
    {
    	if (p_bIncludeDoubleQuotes == true)
    	{
    		return "\"" + p_strCSV.splitCSV().sort().join("\",\"") + "\"";
    	}
    	else
    	{
    		return p_strCSV.splitCSV().sort().join(",")
    	}
    
    }
    
    // Sort a selected CSV string (or an entire draft if there is no selection) and optionally wrap all content in double quotes
    // If there's any chance your content contains non-separator comms, you must set this to true
    function sortSelectedCSV(p_bIncludeDoubleQuotes)
    {
    	if (editor.getSelectedText.length != 0)
    	{
    		editor.setSelectedText(sortCSV(editor.getSelectedText(), p_bIncludeDoubleQuotes));
    	}
    	else
    	{
    		editor.setText(sortCSV(editor.getText(), p_bIncludeDoubleQuotes));
    	}
    }
    
    sortSelectedCSV(bDoubleQuotes);

Options

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