30

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?

Community
  • 1
  • 1
Lee Loftiss
  • 3,035
  • 7
  • 45
  • 73

6 Answers6

49

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

Mir-Ismaili
  • 13,974
  • 8
  • 82
  • 100
marionebl
  • 3,342
  • 20
  • 34
15

Since Lodash 3.1.0, there's a _.startCase([string='']) method that transforms any case into capitalized words (start case):

_.startCase('hello_world'); // returns 'Hello World'
_.startCase('hello-world'); // returns 'Hello World'
_.startCase('hello world'); // returns 'Hello World'

There are other useful methods in the String section of Lodash. Read the documentation here.

Arian Acosta
  • 6,491
  • 1
  • 35
  • 32
  • 2
    sidenote: if you want to import only this one function instead of the entire library in react you can use import startCase from 'lodash/startCase' at the top of your file instead of importing the entire library if you're only using it for this one thing. – jimmyplaysdrums Jun 05 '20 at 22:32
8

These are two different tasks, so two different regexes is the best solution:

key = key.replace(/_/g, ' ').replace(/(?: |\b)(\w)/g, function(key) { return key.toUpperCase()});

To ensure even all capital words is processed. You can add .toLowerCase() before the very first .replace:

console.log('TESTING_WORD'.toLowerCase().replace(/_/g, ' ')
.replace(/(?: |\b)(\w)/g, function(key, p1) {
    return key.toUpperCase();    
}));
Shinjo
  • 677
  • 6
  • 22
Hubert OG
  • 19,314
  • 7
  • 45
  • 73
  • You can remove the underscore from the second regexp, since they've all been removed. – Barmar Feb 15 '14 at 01:44
  • Thanks for the answer. Unfortunately, as is, it is producing the same results as before; contact_details = ContactDetails; It is not putting the space in there. – Lee Loftiss Feb 15 '14 at 01:58
  • Right, I didn't notice that the second regex also removes spaces. I've edited the code to change that functionality. Now it works as intended, you can check out [here](http://repl.it/Omi). – Hubert OG Feb 15 '14 at 08:10
  • To make it better you can add `key.toLowerCase()` before the very first `key.replace` to ensure even all capital words is processed. – Shinjo Jul 25 '19 at 10:27
4

Another alternative:

camel = "options_page".replace(/(^|_)(\w)/g, function ($0, $1, $2) {
  return ($1 && ' ') + $2.toUpperCase();
});
console.log(camel);

The regular expression:

(^|_)   beginning of the input OR "_" ($1)
(\w)    a word character (short for [a-zA-Z0-9_]) ($2)
g       all occurrences (global)

More about regular expressions : http://www.javascriptkit.com/javatutors/redev.shtml.

4

Simply add .replace('_',' ')

Like this

function toCamel(string){
  return string.replace(/(?:_| |\b)(\w)/g, function($1){return $1.toUpperCase().replace('_',' ');});
}
Sagar Kamble
  • 602
  • 4
  • 12
  • hi, how to make all is in Capital Letter? maybe you make two version, 1 is above and the other one is all in caps. – mastersuse Jun 23 '23 at 02:42
2

Here:

var str = 'Lorem_ipsum_dolor_sit_amet,_consectetur____adipiscing_elit.'
str = str.replace(/_{1,}/g,' ').replace(/(\s{1,}|\b)(\w)/g, function(m, space, letter)
{
  return space + letter.toUpperCase();
})

console.log(str);
Alexandre Perez
  • 3,355
  • 3
  • 21
  • 21