Created
January 8, 2013 06:40
-
-
Save jpetitcolas/4481778 to your computer and use it in GitHub Desktop.
Camelize a string in Javascript. Example: camelize("hello_world") --> "HelloWorld"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Camelize a string, cutting the string by separator character. | |
* @param string Text to camelize | |
* @param string Word separator (underscore by default) | |
* @return string Camelized text | |
*/ | |
function camelize(text, separator) { | |
// Assume separator is _ if no one has been provided. | |
if(typeof(separator) == "undefined") { | |
separator = "_"; | |
} | |
// Cut the string into words | |
var words = text.split(separator); | |
// Concatenate all capitalized words to get camelized string | |
var result = ""; | |
for (var i = 0 ; i < words.length ; i++) { | |
var word = words[i]; | |
var capitalizedWord = word.charAt(0).toUpperCase() + word.slice(1); | |
result += capitalizedWord; | |
} | |
return result; | |
} |
export function camelizeFunction(key,separator = '_'){
return (key.split(separator).map(x=>{let t = x.split('');t[0] = t[0].toUpperCase();return t.join('');})).join(' ');
}
const camelize = (text, separator="_")=> (
text.split(separator)
.map(w=> w.replace(/./, m=> m.toUpperCase()))
.join()
)
Nice, Thanks!
I think you'll need an empty quotes "" in the join command:
const camelize = (text, separator="_")=> (
text.split(separator)
.map(w=> w.replace(/./, m=> m.toUpperCase()))
.join("")
)
My two cents :) :
const camelize = (text, separator = '_') => text
.split(separator)
.reduce((acc, cur) => `${acc}${cur.charAt(0).toUpperCase() + cur.slice(1)}`, '');
Thanks for the base though!
@jpetitcolas, @r72cccp, @gunn, @DaveBitter your code is pascalize not camalize
this code is camalize. why you guys read it machine-readable, not human-readable?
/**
*
* @param {string} text
* @param {string} separator
* @return {string}
*/
function camelize(text, separator = '-') {
let words = text.split(separator);
let result = '';
words.forEach((word, index) => {
if (index === 0) {
word = word.replace(/./, (letter) => letter.toLowerCase());
result += word;
return;
}
word = word.replace(/./, (letter) => letter.toUpperCase());
result += word;
});
return result;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i'm do it simple: