How to capitalize first letter of each word, like a 2-word city?
There's a good answer here:
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
or in ES6:
var text = "foo bar loo zoo moo";
text = text.toLowerCase()
.split(' ')
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(' ');
Capitalize first word of each line
As said before in comments, you need to specify what is new line in your text. Just a new line (\n
) ? Here's an example working only with new lines characters:
var text = document.getElementById("pre").innerText, newText = text .split(/\n/g) .map(x => x.charAt(0).toUpperCase() + x.substr(1)) .join("\n");
console.log(newText);
<pre id="pre">lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ut leo mauris. integer pharetra imperdiet mauris a tempor. cras facilisis pulvinar porta. cras viverra pellentesque dui, ut pulvinar ex commodo eu. curabitur sodales vitae velit ut luctus. aliquam diam justo, facilisis vitae facilisis nec, commodo ut nunc. duis bibendum, sem laoreet mollis laoreet, ipsum velit pulvinar magna, quis accumsan leo felis id lorem. proin et suscipit dui. duis porttitor nibh non faucibus pretium.</pre>
Auto Capitalize ONLY the First Letter of Each Word in an Input Field
See comments inline for details:
// Get a reference to the input and wire it up to an input event handler that// calls the fixer functiondocument.getElementById("txtTest").addEventListener("input", forceLower);
// Event handling functions are automatically passed a reference to the// event that triggered them as the first argument (evt)function forceLower(evt) { // Get an array of all the words (in all lower case) var words = evt.target.value.toLowerCase().split(/\s+/g); // Loop through the array and replace the first letter with a cap var newWords = words.map(function(element){ // As long as we're not dealing with an empty array element, return the first letter // of the word, converted to upper case and add the rest of the letters from this word. // Return the final word to a new array return element !== "" ? element[0].toUpperCase() + element.substr(1, element.length) : ""; }); // Replace the original value with the updated array of capitalized words. evt.target.value = newWords.join(" "); }
<input type="text" id="txtTest">
How can I capitalize the first letter of each word in a string?
The .title()
method of a string (either ASCII or Unicode is fine) does this:
>>> "hello world".title()
'Hello World'
>>> u"hello world".title()
u'Hello World'
However, look out for strings with embedded apostrophes, as noted in the docs.
The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
How to capitalize the first letter of word in a string using Java?
If you only want to capitalize the first letter of a string named input
and leave the rest alone:
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
Now output
will have what you want. Check that your input
is at least one character long before using this, otherwise you'll get an exception.
capitalizing only first letter in a contraction
Your problem seems to be that you are using a global match in your replacer expression.
Remove the g
.
function titleCase(str) { str = str.toLowerCase(); // Make everything lowercase str = str.split(/\s+/); // Make the string to array for (var i = 0; i < str.length; i++) { var strItem = str[i]; // Take item in array strItem = strItem.replace(/\b./, function(m) { return m.toUpperCase(); // Capitalize it } ); str[i] = strItem; // Put changed item back into array } return str.join(" "); // Turn array back into string}
document.body.innerHTML = titleCase("I'm a little tea pot");
Related Topics
Sending Credentials with Cross-Domain Posts
Jquery Checkbox Checked State Changed Event
How to Get Evaluated Attributes Inside a Custom Directive
Three.Js Generate Uv Coordinate
How to Get Notified About Changes of the History via History.Pushstate
How to Use React Hooks in React Classic 'Class' Component
Moment Js Date Time Comparison
Idiomatically Find the Number of Occurrences a Given Value Has in an Array
How to Run Two Jquery Animations Simultaneously
Merge JavaScript Objects in Array with Same Key
Remove All White Spaces from Text
How to Profile JavaScript Execution
How Can Jquery Deferred Be Used
Are Es6 Classes Just Syntactic Sugar for the Prototypal Pattern in JavaScript
Making Custom Right-Click Context Menus for My Web-App