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?
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With