Is there a reg exp or function that will convert camel case, css and underscore to human readable format? It does not need to support non-humans at this time. Sorry aliens. :(
Examples:
helloWorld -> "Hello World"
hello-world -> "Hello World"
hello_world -> "Hello World"
Split by non-words; capitalize; join:
function toCapitalizedWords(name) {
var words = name.match(/[A-Za-z][a-z]*/g) || [];
return words.map(capitalize).join(" ");
}
function capitalize(word) {
return word.charAt(0).toUpperCase() + word.substring(1);
}
Extract all words with a regular expression. Capitalize them. Then, join them with spaces.
Example regexp:
/^[a-z]+|[A-Z][a-z]*/g
/ ^[a-z]+ // 1 or more lowercase letters at the beginning of the string
| // OR
[A-Z][a-z]* // a capital letter followed by zero or more lowercase letters
/g // global, match all instances
Example function:
var camelCaseToWords = function(str){
return str.match(/^[a-z]+|[A-Z][a-z]*/g).map(function(x){
return x[0].toUpperCase() + x.substr(1).toLowerCase();
}).join(' ');
};
camelCaseToWords('camelCaseString');
// Camel Case String
camelCaseToWords('thisIsATest');
// This Is A Test
Here is the ActionScript version based on the idea from Ricks C example code. For JavaScript version remove the strong typing. For example, change var value:String
to var value
. Basically remove any declaration that starts with a semicolon, :String
, :int
, etc.
/**
* Changes camel case to a human readable format. So helloWorld, hello-world and hello_world becomes "Hello World".
* */
public static function prettifyCamelCase(value:String=""):String {
var output:String = "";
var len:int = value.length;
var char:String;
for (var i:int;i<len;i++) {
char = value.charAt(i);
if (i==0) {
output += char.toUpperCase();
}
else if (char !== char.toLowerCase() && char === char.toUpperCase()) {
output += " " + char;
}
else if (char == "-" || char == "_") {
output += " ";
}
else {
output += char;
}
}
return output;
}
JavaScript version:
/**
* Changes camel case to a human readable format. So helloWorld, hello-world and hello_world becomes "Hello World".
* */
function prettifyCamelCase(str) {
var output = "";
var len = str.length;
var char;
for (var i=0 ; i<len ; i++) {
char = str.charAt(i);
if (i==0) {
output += char.toUpperCase();
}
else if (char !== char.toLowerCase() && char === char.toUpperCase()) {
output += " " + char;
}
else if (char == "-" || char == "_") {
output += " ";
}
else {
output += char;
}
}
return output;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With