473,696 Members | 1,922 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

split camelcase string into array of words words

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.
Thanks.

Jul 21 '06 #1
10 11935

"pantagruel " <ra************ *@gmail.comwrot e in message
news:11******** **************@ i3g2000cwc.goog legroups.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.prototyp e.CamelCaseToAr ray = function() {
// Preceed Uppercase (or sets of) with commas then remove any
leading comma
var Delimed = this.replace(/([A-Z]+)/g, ",$1").repl ace(/^,/, "");
// 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 = "MyCamelCASEStr ing";

alert(TestStrin g.CamelCaseToAr ray());

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
Jul 21 '06 #2
pantagruel wrote:
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.
Thanks.
"CamelCaseStrin g".match(/[A-Z][a-z]*/g)

returns array:

("Camel", "Case", "String").

Seems like what you want :-)

Jeremy
Jul 21 '06 #3
"Jeremy" <je****@pinacol .comwrote in message
news:%F7wg.1463 2$Nv.7608@fed1r ead10...
pantagruel wrote:
>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.

"CamelCaseStrin g".match(/[A-Z][a-z]*/g)

returns array:

("Camel", "Case", "String").

Seems like what you want :-)
But this:

"camelCaseStrin g".match(/[A-Z][a-z]*/g)

Returns: ["Case", "String"].

And this:

"camelCaseSTRIN G".match(/[A-Z][a-z]*/g)

Returns: ["Case", "S", "T", "R", "I", "N", "G"]

So... well... neener neener neener. ;^)

(Yeah... I'm a big jackass.)

Jim Davis
Jul 21 '06 #4
>
Here's an example of how you might use it:

TestString = "MyCamelCASEStr ing";

alert(TestStrin g.CamelCaseToAr ray());

Haven't tested yet but on appearance looks like it will work with the
strings I have to deal with, upper and lower camel cased strings that
need to be split into words. Since there is no punctuation allowed in
the strings I can't see this as being a problem.

Thanks for the help, will credit you in the comments of the script.

Cheers,
Bryan Rasmussen

Jul 21 '06 #5
Jim Davis wrote:
>
But this:

"camelCaseStrin g".match(/[A-Z][a-z]*/g)

Returns: ["Case", "String"].

And this:

"camelCaseSTRIN G".match(/[A-Z][a-z]*/g)

Returns: ["Case", "S", "T", "R", "I", "N", "G"]

So... well... neener neener neener. ;^)

(Yeah... I'm a big jackass.)

Jim Davis

Those aren't camel case strings, now are they? :-) You can't expect any
algorithm that targets camel case strings to work on non-camel-case strings.

Jeremy

Jul 21 '06 #6
Jeremy wrote:
Jim Davis wrote:
>>
But this:

"camelCaseStri ng".match(/[A-Z][a-z]*/g)

Returns: ["Case", "String"].

And this:

"camelCaseSTRI NG".match(/[A-Z][a-z]*/g)

Returns: ["Case", "S", "T", "R", "I", "N", "G"]

So... well... neener neener neener. ;^)

(Yeah... I'm a big jackass.)

Jim Davis

Those aren't camel case strings, now are they? :-) You can't expect any
algorithm that targets camel case strings to work on non-camel-case
strings.

Jeremy
Besides, by tweaking the regex a little you can account for
lower-camel-case:

"lowerCamelCase ".match(/[A-Z]?[a-z]+/g)

returns {"lower", "Camel", "Case"}

Anything else (i.e. "camelCaseSTRIN G") is not a camel case string. I
would argue that in this case STRING must be an acronym and there's no
reason it should come back in all one string in the result array.

So, strictly speaking... neener neener :-)

Jeremy
Jul 21 '06 #7
JRS: In article <ks************ *************** ***@giganews.co m>, dated
Fri, 21 Jul 2006 13:35:43 remote, seen in news:comp.lang. javascript, Jim
Davis <ne********@vbo ston.composted :
>"Jeremy" <je****@pinacol .comwrote in message
news:%F7wg.146 32$Nv.7608@fed1 read10...
>pantagruel wrote:
>>I'm looking for an optimal javascript function to split a camelcase
string and return an array.
>"CamelCaseStri ng".match(/[A-Z][a-z]*/g)

returns array:

("Camel", "Case", "String").

Seems like what you want :-)

But this:

"camelCaseStri ng".match(/[A-Z][a-z]*/g)

Returns: ["Case", "String"].

But this : "camelCaseStrin g".match(/(\b|[A-Z])[a-z]*/g)
returns ['camel','Case', 'String']

And this : "camelCaseSTRin g".match(/(\b|[A-Z]+)[a-z]*/g)
returns ['camel','Case', 'STRing']

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/>? JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 21 '06 #8
Dr John Stockton wrote:
>
But this : "camelCaseStrin g".match(/(\b|[A-Z])[a-z]*/g)
returns ['camel','Case', 'String']

And this : "camelCaseSTRin g".match(/(\b|[A-Z]+)[a-z]*/g)
returns ['camel','Case', 'STRing']
What does \b do? Never seen that before.

Jeremy
Jul 21 '06 #9
"Dr John Stockton" <jr*@merlyn.dem on.co.ukwrote in message
news:Ar******** ******@merlyn.d emon.co.uk...
JRS: In article <ks************ *************** ***@giganews.co m>, dated
Fri, 21 Jul 2006 13:35:43 remote, seen in news:comp.lang. javascript, Jim
Davis <ne********@vbo ston.composted :
>>"Jeremy" <je****@pinacol .comwrote in message
news:%F7wg.14 632$Nv.7608@fed 1read10...
>>pantagruel wrote:
>snip<
But this : "camelCaseStrin g".match(/(\b|[A-Z])[a-z]*/g)
returns ['camel','Case', 'String']

And this : "camelCaseSTRin g".match(/(\b|[A-Z]+)[a-z]*/g)
returns ['camel','Case', 'STRing']
No - that doesn't count. You didn't say "neener neener". ;^)

Jim Davis
Jul 22 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
31176
by: Stu Cazzo | last post by:
I have the following: String myStringArray; String myString = "98 99 100"; I want to split up myString and put it into myStringArray. If I use this: myStringArray = myString.split(" "); it will split myString up using the delimiter of 1 space so that
2
1765
by: John Benson | last post by:
I never cared for CamelCase because a lot of words in English are compounds, and remembering the right CamelCase rendition of them gets difficult. For example, an object attribute named HaveAMerryChristmas isn't too hard, but what about deciding between HaveAGoodWeekend
5
57192
by: Vamsi | last post by:
Hi, I am trying a basic opearation of splitting a multiline value to an array of single lines(Actually making Address into AddressLine1, AddressLine2). I used Environment.NewLine in split, I could get only 1st line, but it is not returning 2nd line. here's code: string address = null; string ssep = Environment.NewLine; char sep = ssep.ToCharArray();
3
2098
by: John Salerno | last post by:
This is an example in the book I'm reading: string fullName = " Edward C Koop "; fullName = fullName.Trim(); string names = fullName.Split(' '); string firstName = names; // Edward Two questions about this: 1. Why do you use single quotes with Split() instead of double? Is this
8
14190
by: Dave | last post by:
Greetings, Is there a way I can split a string into an array on a space OR a carriage return? What would the code look like for this? Thanks, -Dave
3
9665
by: Ben | last post by:
Hi I am creating a dynamic function to return a two dimensional array from a delimeted string. The delimited string is like: field1...field2...field3... field1...field2...field3... field1...field2...field3...
6
2167
by: Saurabh | last post by:
Hi everyone, I am looking for some expert advise to get me out of trouble. I am looking for a solution in C# which will allow me to split the below string in the format provided. The String.Split() allows only a single char as a delimiter.So I cannot use that as well. Original String "*** MASTER (Supervisor) *** September 23, 1997 at 3:22pm \r\nThis is the first line of text. There will be many more beneath this on so look...
2
5888
by: pmwhelan | last post by:
Hi I want to split a string into an array and treat quoted phrases as words. I was splitting on a space which worked fine. char delimiterChars = {' '}; string arrValues = searchText.Split(delimiterChars); This would split a sentence ... this is a test
3
186
by: shapper | last post by:
Hello, I have a string as follows: string text = "Paris, New York , London,Lisbon,Oslo, Chicago "; I need to get all words with no commas or spaces: "Paris", "New", "York", "London", "Lisbon", "Oslo", "Chicago" I am using (I think it is ok):
0
8656
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8592
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9005
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8871
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8846
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6512
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5851
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4351
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2306
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.