Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to Pascal Case (aka UpperCamelCase) in Javascript

Id like to know how I can covert a string into a pascal case string in javascript (& most probally regex).

Conversion Examples:

  • double-barrel = Double-Barrel
  • DOUBLE-BARREL = Double-Barrel
  • DoUbLE-BaRRel = Double-Barrel
  • double barrel = Double Barrel

Check this link for further info on Pascal Case

like image 710
Blowsie Avatar asked Nov 01 '10 11:11

Blowsie


People also ask

What is Pascal case in JavaScript?

Pascal case -- or PascalCase -- is a programming naming convention where the first letter of each compound word in a variable is capitalized. The use of descriptive variable names is a software development best practice. However, modern programming languages do not allow variables names to include blank spaces.

How do you use camel case in JavaScript?

Approach: Use str. replace() method to replace the first character of string into lower case and other characters after space will be into upper case. The toUpperCase() and toLowerCase() methods are used to convert the string character into upper case and lower case respectively.


1 Answers

s = s.replace(/(\w)(\w*)/g,         function(g0,g1,g2){return g1.toUpperCase() + g2.toLowerCase();}); 

The regex finds words (here defined using \w - alphanumerics and underscores), and separates them to two groups - first letter and rest of the word. It then uses a function as a callback to set the proper case.

Example: http://jsbin.com/uvase

Alternately, this will also work - a little less regex and more string manipulation:

s = s.replace(/\w+/g,         function(w){return w[0].toUpperCase() + w.slice(1).toLowerCase();}); 

I should add this isn't pascal case at all, since you have word barriers (helloworld vs hello-world). Without them, the problem is almost unsolvable, even with a dictionary. This is more commonly called Title Case, though it doesn't handle words like "FBI", "the" or "McDonalds".

like image 195
Kobi Avatar answered Oct 06 '22 09:10

Kobi