Domanda

I am stuck with creating custom humanize function for my project. My API is returing labels that I want to turn into more readable such as:

probabilityOfDefault

and I want to change it into

Probability Of Default

or

historicalDate

and change it into

Historical Date

So far I have written a function but it only changes the letters to upper case, it doesnt add space before every each. Here it is:

var humanize = function(property) {
  return property.replace(/_/g, ' ')
  .replace(/(\w+)/g, function(match) {
    return match.charAt(0).toUpperCase() + match.slice(1);
  });
};

I am not an expert in regular expersions, also I am not unaware of any libaries that could do this for me. Any help ?

È stato utile?

Soluzione

You can use:

s = 'probabilityOfDefault';
r = s[0].toUpperCase() + s.substring(1).replace(/([a-z])(?=[A-Z])/g, "$1 ");
//=> Probability Of Default
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top