Solved

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

Posted on 2010-09-23
13
781 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
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)

919 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

16 Experts available now in Live!

Get 1:1 Help Now