Solved

Javascript with Regular Expression to extract string and convert to camel case

Posted on 2010-09-23
13
770 Views
Last Modified: 2012-05-10
I need the fastest pattern possible to convert a string in a particular format to camel case. I am trying to avoid using Javascript replace() when possible in favor of a regular expression for performance reasons. Since this method can get called several times per second, it needs to be efficient. Basically, I need to convert a string like:

     wordone-wordtwo-wordthree

to:

     wordtwoWordthree

So, there are an undetermined number of words separated by hyphens. I need to eliminate the first word, leave the second word intact, and capitalize every word after (camel case). Like I said I would prefer if all this could be done with a regular expression for performance purposes, but I understand the capitalizing the first letter would probably not be possible in the regex, so this part can be done with javascript. The capitalization part needs to also use the most efficient method possible.

Thanks!
0
Comment
Question by:exalkonium
  • 6
  • 5
  • 2
13 Comments
 
LVL 41

Expert Comment

by:HonorGod
ID: 33748458
Like this?
<html>
<body>

<script type='text/javascript'>
function camelcase( str ) {
  var words = str.split( '-' );
  for ( var i = 0; i < words.length; i++ ) {
    words[ i ] = words[ i ].substr( 0, 1 ).toUpperCase() + words[ i ].substr( 1 ).toLowerCase();
  }
  return words.join( '' );
}

document.write( camelcase( 'wordone-wordtwo-wordthree' ) )
</script>

</body>
</html>

Open in new window

0
 
LVL 41

Expert Comment

by:HonorGod
ID: 33748474
Oh, did you really want the first word (i.e., "wordone" ) discarded?

And if you don't want the 1st word capitalized...
<html>
<body>

<script type='text/javascript'>
function camelcase( str ) {
  var words = str.split( '-' );
  for ( var i = 1; i < words.length; i++ ) {
    words[ i ] = words[ i ].substr( 0, 1 ).toUpperCase() + words[ i ].substr( 1 ).toLowerCase();
  }
  return words.join( '' );
}

document.write( camelcase( 'wordone-wordtwo-wordthree' ) )
</script>

</body>
</html>

Open in new window

0
 
LVL 9

Author Comment

by:exalkonium
ID: 33748671
Do you think the performance of splitting would be faster than a regular expression? Just an opinion...
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33748845
Check this :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script language="javascript">
	var s = "wordone-wordtwo-wordthree-Wordfour-wooooordfive";
//	s = s.substr(s.indexOf("-")).replace(/^(.)|-(.)/g, function($1) { return $1.replace("-","").toUpperCase(); });
	s = s.substr(s.indexOf("-")).replace(/^(.)|-(.)/g, function($1) { return $1.charAt(1).toUpperCase(); });
	alert( s );
</script>
</body>
</html>

Open in new window

0
 
LVL 9

Author Comment

by:exalkonium
ID: 33749022
Good suggestions, but none of the scripts I have tried have been able to perform better than this one. Do you see any way that it can be improved or is this the best it's going to get? It's basically a modified version of the one from HonorGod:
var words = string.split('-');
	var newWords = [];
	var i = words.length;
	while (i--) {
		if (i != 0) {
			var word = words[i];
			if (i != 1)
				word = word.substr(0, 1).toUpperCase() + word.substr(1);

			newWords.push(word);
		}
	}

	return newWords.reverse().join();

Open in new window

0
 
LVL 9

Author Comment

by:exalkonium
ID: 33749070
Sorry, forgot to post the updated version:
var toCamelCase = function(string) {
   var words = string.split('-');
   var newWords = [];
   var i = words.length;
   
   while (i-- && i > 0) {
      var word = words[i];
      if (i != 1)
         word = word.substr(0, 1).toUpperCase() + word.substr(1);
   
      newWords.push(word);
   }

   return newWords.reverse().join();
}

Open in new window

0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 9

Author Comment

by:exalkonium
ID: 33749080
The join method above is supposed to have an empty string. Pretend its there .join('')
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33749490
I was thinking you want the fastest regex. Regex is not fast.

Run this :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script language="javascript">
var d1 = new Date();

	var s = "wordone";
	for(var i=0;i<=2000000;i++) {
		s += "-word"+i;
	}

   var words = s.split('-');
   var newWords = [];
   var i = words.length;
   
   while (i-- && i > 0) {
      var word = words[i];
      if (i != 1)
         word = word.substr(0, 1).toUpperCase() + word.substr(1);
   
      newWords.push(word);
   }
   
   str = newWords.reverse().join();

var d2 = new Date();
alert(d2-d1);
</script>
</body>
</html>

Open in new window

0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 33749497
And this :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script language="javascript">
var d1 = new Date();

	var s = "wordone";
	for(var i=0;i<=2000000;i++) {//2000000
		s += "-word"+i;
	}
	var str = s.split("-");
	var fst = str[1];
	for(var i=2;i<str.length;i++) fst += str[i].substr(0, 1).toUpperCase() + str[i].substr(1);
	
var d2 = new Date();
alert(d2-d1);
</script>
</body>
</html>

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 33749505
I get for the first (your last code) : 2696
For mine : 1952
0
 
LVL 9

Author Comment

by:exalkonium
ID: 33749722
You are right. The code I used performed even slower than just using replace. Your code is even faster than that. Thanks!
0
 
LVL 9

Author Closing Comment

by:exalkonium
ID: 33749748
Thanks.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33749758
You're welcome! Thanks for the points!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Article by: Nadia
Linear search (searching each index in an array one by one) works almost everywhere but it is not optimal in many cases. Let's assume, we have a book which has 42949672960 pages. We also have a table of contents. Now we want to read the content on p…
The greatest common divisor (gcd) of two positive integers is their largest common divisor. Let's consider two numbers 12 and 20. The divisors of 12 are 1, 2, 3, 4, 6, 12 The divisors of 20 are 1, 2, 4, 5, 10 20 The highest number among the c…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now