"pantagruel" <ra*************@gmail.comwrote in message
news:11**********************@i3g2000cwc.googlegro ups.com...
Hi,
I'm looking for an optimal javascript function to split a camelcase
string and return an array.
I suppose one could loop through the string, check if character is
uppercase and start building a new word to add to the array but that
seems incredibly wasteful. must be some easy way to do it.
This was a fun little morning brain warmer. ;^)
I've created a function that, I think, will do what you want. It's not that
pretty but it seem to work. In my example I've added it to String prototype
(making it available to all strings) but you can put it anyplace you like...
you could also condense it down to one line of code and append it to any
string but don't do that: functions should be used to abstract ugly code
like this. ;^)
Here it is:
String.prototype.CamelCaseToArray = function() {
// Preceed Uppercase (or sets of) with commas then remove any
leading comma
var Delimed = this.replace(/([A-Z]+)/g, ",$1").replace(/^,/, "");
// Split the string on commas and return the array
return Delimed.split(",");
};
Basically this does a regular expression search for uppercase letters (or
sets of uppercase letters) and preceeds them with commas. Since the string
may now have a comma as it's first character another replace is done to
remove it (if it exists). Then the whole mess is split on the commas and
returned.
Here's an example of how you might use it:
TestString = "MyCamelCASEString";
alert(TestString.CamelCaseToArray());
This function will (I hope obviously) have problems if there are commas in
the string to begin with. I've tested it on a handful of strings but you
should vette it more before trusting it.
I think (since I'm only caring to look for uppercase characters) that it
should be blissfully unfazed by numbers and punctuation (other than the
comma).
Hope this helps,
Jim Davis