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
Solved

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

Posted on 2010-09-23
13
796 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
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Button and js nou working 3 19
Multiflying 2 Input Text On a Table 7 31
RegEx with optional part 4 42
jQuery Dialog Autoresize Bug 2 24
Article by: Nadia
Suppose you use Uber application as a rider and you request a ride to go from one place to another. Your driver just arrived at the parking lot of your place. The only thing you know about the ride is the license plate number. How do you find your U…
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…
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…

765 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