Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2010-09-23
13
Medium Priority
?
846 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 83

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
 
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 83

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 83

Accepted Solution

by:
leakim971 earned 2000 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 83

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 83

Expert Comment

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

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

Question has a verified solution.

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

Iteration: Iteration is repetition of a process. A student who goes to school repeats the process of going to school everyday until graduation. We go to grocery store at least once or twice a month to buy products. We repeat this process every mont…
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
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…
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…

926 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