I'm trying to replicate CI's humanize()
and underscore()
function in Javascript.
From the CI documentation, underscore()
takes multiple words separated by spaces and underscores them while humanize()
takes multiple words separated by underscores and adds spaces between them. The CI implementation looks something like:
function underscore($str) {
return preg_replace('/[\s]+/', '_', strtolower(trim($str)));
}
function humanize($str) {
return ucwords(preg_replace('/[_]+/', ' ', strtolower(trim($str))));
}
My code doesn't have to replicate the behavior exactly, but for the underscore()
function I'd like it to be able to deal with multiple whitespace characters, while the humanize()
function can be a bit looser and assume that only one underscore will only be there to separate each word.
So far what I have is:
function underscore(string) {
string = $.trim(string).toLowerCase();
var oldString;
while(oldString !== string){
oldString = string;
string = string.replace(/\s+/, '_');
}
return string;
}
function humanize(string) {
string = $.trim(string);
var terms = string.split('_');
for(var i=0; i < terms.length; i++){
terms[i] = terms[i].charAt(0).toUpperCase() + terms[i].slice(1);
}
return terms.join(' ');
}
Which works fine, yes, but I don't really like the way I did this (It's way too long compared to the PHP. There must be a more compact version), so I'm wondering if there's a more efficient / readable method to achieve this.