1

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 ?

Michał Lach
  • 1,209
  • 4
  • 17
  • 33

1 Answers1

2

You can use:

s = 'probabilityOfDefault';
r = s[0].toUpperCase() + s.substring(1).replace(/([a-z])(?=[A-Z])/g, "$1 ");
//=> Probability Of Default
anubhava
  • 664,788
  • 59
  • 469
  • 547
  • I have more extreme example like: 'Some1e1A3String A1C' change it into 'Some 1E 1A3 String A1C', can you make it work ? – Michał Lach Mar 27 '14 at 10:07
  • Hmm that changes the question a lot. You can try: `'Some1e1A3String'.replace(/([a-z])(?=[0-9A-Z])|([0-9])(?=[A-Z][a-z])/g, "$1$2 ")` – anubhava Mar 27 '14 at 10:12