Replace underscores with spaces and capitalize words

javascript, regex

Solution

This should do the trick:

function humanize(str) {
  var i, frags = str.split('_');
  for (i=0; i<frags.length; i++) {
    frags[i] = frags[i].charAt(0).toUpperCase() + frags[i].slice(1);
  }
  return frags.join(' ');
}


console.log(humanize('humpdey_dumpdey'));
// > Humpdey Dumpdey

repl

http://repl.it/OnE

Fiddle:

http://jsfiddle.net/marionebl/nf4NG/

jsPerf:

Most test data: http://jsperf.com/string-transformations

All versions plus _.str: http://jsperf.com/string-transformations/3

Problem

I am attempting to create a way to convert text with lowercase letters and underscores into text without underscores and the first letter of each word is capitalized. ex; ``` options_page = Options Page ``` At this page: How to make first character uppercase of all words in JavaScript? I found this regex: ``` key = key.replace(/(?:_| |\b)(\w)/g, function(key, p1) { return p1.toUpperCase()}); ``` This does everything except replace the underscores with spaces. I have not really tried anything because I am not that familiar with regexpressions. How can I adjust this regex so it replaces underscores with spaces?

Original source

Related problems