Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace underscores with spaces and capitalize words

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?

like image 737
Lee Loftiss Avatar asked Feb 15 '14 01:02

Lee Loftiss


People also ask

How do I replace a space underscore?

Use the String. replaceAll method to replace all spaces with underscores in a JavaScript string, e.g. string. replaceAll(' ', '_') . The replaceAll method returns a new string with all whitespace characters replaced by underscores.

How do you remove underscore from a string?

To remove the underscores from a string, call the replaceAll() method on the string, passing it an underscore as the first parameter, and an empty string as the second, e.g. replaceAll('_', '') . The replaceAll method will return a new string, where all underscores are removed.

How do you capitalize the first letter in JavaScript?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.


2 Answers

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

like image 94
marionebl Avatar answered Sep 24 '22 14:09

marionebl


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.

like image 41
Arian Acosta Avatar answered Sep 22 '22 14:09

Arian Acosta