Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to Title Case with JavaScript

Is there a simple way to convert a string to Title Case? E.g. john smith becomes John Smith. I'm not looking for something complicated like John Resig's solution, just (hopefully) some kind of one- or two-liner.

like image 976
MDCore Avatar asked Oct 13 '08 08:10

MDCore


People also ask

How do you change a string to a case in Java?

Java String toLowerCase() MethodThe toLowerCase() method converts a string to lower case letters. Note: The toUpperCase() method converts a string to upper case letters.

How do you capitalize in JavaScript?

To capitalize an entire string, simply call . toUpperCase() on the string: let myString = 'alligator'; myString.


1 Answers

Try this:

function toTitleCase(str) {   return str.replace(     /\w\S*/g,     function(txt) {       return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();     }   ); }
<form>   Input:   <br /><textarea name="input" onchange="form.output.value=toTitleCase(this.value)" onkeyup="form.output.value=toTitleCase(this.value)"></textarea>   <br />Output:   <br /><textarea name="output" readonly onclick="select(this)"></textarea> </form>
like image 55
Greg Dean Avatar answered Sep 20 '22 19:09

Greg Dean