faqts : Computers : Programming : Languages : JavaScript : Language Core : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 6 people (50%) answered Yes
Recently 3 of 6 people (50%) answered Yes

Entry

How does one split a string with different delimiters into multiple nested arrays?

Aug 9th, 2004 11:15
Eric Greenblatt, Gregor Jennings,


Try this:
function multiSplit(str)
{
   var splitters = null;
   var retVal = null;
   var i=0;
   // we need something to split on
   // if we don't get one, then return a single element
   if (arguments.length<2)
   {
      return new Array(str);
   }
   if (typeof(arguments[1])=='string')
   {
      splitters=arguments;
      // filter out the str
      splitters.splice(0,1);
   }
   // otherwise, make sure we got an array of splitters
   else if (arguments[1].constructor == window.Array)
   {
      splitters=arguments[1];
   } else
   {
      return new Array(str);
   }
   // split str using the first splitter
   retVal=str.split(splitters[0]);
   // if there are additional splitters,
   // then each element in retVal becomes an array
   if (splitters.length>1)
   {
      // strip off this splitter
      splitters.splice(0,1);
      for (i=0; i<retVal.length; i++)
      {
         // drill down with the rest
         retVal[i]=multiSplit(retVal[i],splitters);
      }
   }
   // return the array [of arrays...]
   return retVal;
}
String.prototype.multiSplit = function(splitters){
  return multiSplit (this,splitters);};
----
<table border="1">
<script type="text/javascript">
var splitText="Hello there.\nHow are you?\nI am fine, thanks.";
var arr=splitText.multiSplit(splitters,'\n',' ');
var r=0, c=0;
if (typeof(arr[0])=='string')
{
   document.write('<TR><TD>'+arr+'</TD></TR>');
} else
{
   for (r=0; r<arr.length; r++)
   {
      document.writeln('<TR>');
      for (c=0; c<arr[r].length; c++)
      {   
         document.writeln('<TD>'+arr[r][c]+'</TD>');
      }
      document.writeln('</TR>');
   }
}
</SCRIPT>
</table>
HTH -- sMyles, evry1
Eric