Reputation: 17806
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"
Upvotes: 16
Views: 15125
Reputation: 111
const result = _.chain("hello-world")
.snakeCase()
.split("_")
.map(w => _.capitalize(w))
.join(" ")
.value()
console.log(result)
<script src="
https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js
"></script>
Upvotes: 1
Reputation: 2399
If using a library is an option, Lodash
's startCase
or lowerCase
might be useful:
https://lodash.com/docs/#startCase
https://lodash.com/docs/#lowerCase
Upvotes: 2
Reputation: 185
Non elegant one liner using regex replaces with functions.
replace 1 - upper case first letter and remove _-
replace 2 - add space between lower case letters and upper case letters
var titleCase = s => s
.replace(/(^|[_-])([a-z])/g, (a, b, c) => c.toUpperCase())
.replace(/([a-z])([A-Z])/g, (a, b, c) => `${b} ${c}`);
console.log(titleCase("helloWorld"));
console.log(titleCase("hello-world"));
console.log(titleCase("hello_world"));
Upvotes: 2
Reputation: 225054
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);
}
Upvotes: 34
Reputation: 17806
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;
}
Upvotes: 3
Reputation: 4261
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
Upvotes: 12
Reputation: 561
I don't know if there is already a built in method to do this but you could loop through the string and every time you see a character that you want to split on do so.
In your case something like:
my_str = 'helloWorld';
returnString = '';
for(var i = 0; i < my_str.length; i++) {
if(i == 0) {
returnString += (my_str[i] + 32); // capitalize the first character
}
else if(my_str[i] > 'A' || my_str[i] < 'Z') {
returnString += ' ' + my_str[i]; // add a space
}
else if(my_str[i] == '-' || my_str[i] == '_') {
returnString += ' ';
}
else {
returnString += my_string[i];
}
}
return returnString;
Edit:
After the numerous comments I have come to realize that I put up some broken code :P
Here is a tested version of it:
my_str = 'helloWorld';
function readable(str) {
// and this was a mistake about javascript/actionscript being able to capitalize
// by adding 32
returnString = str[0].toUpperCase();
for(var i = 1; i < str.length; i++) {
// my mistakes here were that it needs to be between BOTH 'A' and 'Z' inclusive
if(str[i] >= 'A' && str[i] <= 'Z') {
returnString += ' ' + str[i];
}
else if(str[i] == '-' || str[i] == '_') {
returnString += ' ';
}
else {
returnString += str[i];
}
}
return returnString;
}
Upvotes: 2
Reputation: 74078
You can use a replacement function for String.replace, e.g.
function capitalize(s) {
return s[0].toUpperCase() + s.slice(1);
}
function replacer1(match, p1, p2, p3, offset, s) {
return p1 + capitalize(p2) + ' ' + p3;
}
var s1 = "helloWorld";
var r1 = s1.replace(/(^|[^a-z])([a-z]+)([A-Z])/, replacer1);
console.log(r1);
hello-world
and hello_world
work similar.
See JSFiddle
Upvotes: 2