Beginner to Beginner: Splitting strings into arrays in Javascript
I mentioned to my nephew Joel Weinberger, a CS grad student at UC Berkeley, that I wished the Javascript “split” method took multiple delimiters, and within minutes, he wrote one for me. If you know what I’m talking about, you can click here to get a zip file with the code (including a function as well as a method) and a sample. If you don’t …
[Note: all explanations are approximate.] Javascript comes with a built-in method for converting a string (that is, what normally consists of letters and characters in quotes) into an array (that is, a data structure of numbered elements). So, if you have a string that’s really a list of elements, such as “monday, tuesday, wednesday” or “12-345-6,” the split method will automatically chop it up into an array, using a delimiter of your choice (a comma or a dash in the two examples given). This is very useful.
But suppose you have a string such as this: “beef OR chicken AND duck” You want to be able to chop it up at the ORs and the ANDs, but the split method only lets you specify one delimiter.
Enter Joel. His multiSplit method lets you specify an array of delimiters. It chops up the string and records the phrases and their delimiters. Very handy.
Thanks, Joel!
Categories: Uncategorized dw