Solved

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

Posted on 2010-09-23
13
827 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

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

Independent Software Vendors: 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!

Question has a verified solution.

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

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
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 code hide show and toggles. 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…
Suggested Courses

635 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