title: Method for splitting string into separate cells in Sheets / App Script
body: <p>I'm trying to split a string into separate cells, but the order of substrings will be different to how it appears in the string originally. Not all parts of the string are necessary and the length of each substring isn't static. I managed to achieve something workable on a separate project where the substring lengths were static using lastIndexOf but it was incredibly clunky.</p>
  
  <p>I'm hoping that someone could point me to a better way of approaching the problem.</p>
  
  <p>Each string of data will look like this:</p>
  
  <pre><code>01|020202|03|0404040404|05|0606060606|
  </code></pre>
  
  <p>My previous code was equivalent to this:</p>
  
  <pre><code>function splitString() {
  
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheet = ss.getSheetByName("Data");
   var input = sheet.getRange(2,4).getValue(); 
  
   var data1 = input.substring(input.lastIndexOf("!")-5,input.lastIndexOf("|")-1);
   var data2 = input.substring(input.lastIndexOf("|")-10, data1);
  
   // etc.
  
   sheet.getRange(3,2).setValue(data1);
   sheet.getRange(4,2).setValue(data2);
  
   // etc.
  
  }
  </code></pre>
  
  <p>Can anybody suggest a better method for doing this? Any help would be much appreciated.</p>