How can I capitalize the first letter of each word in a string using JavaScript?
You are not assigning your changes to the array again, so all your efforts are in vain. Try this:
function titleCase(str) { var splitStr = str.toLowerCase().split(' '); for (var i = 0; i < splitStr.length; i++) { // You do not need to check if i is larger than splitStr length, as your for does that for you // Assign it back to the array splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1); } // Directly return the joined string return splitStr.join(' '); }
document.write(titleCase("I'm a little tea pot"));
How to capitalize the first character of each word in a string
WordUtils.capitalize(str)
(from apache commons-text)
(Note: if you need "fOO BAr"
to become "Foo Bar"
, then use capitalizeFully(..)
instead)
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"
Capitalise every word in String with extension function
Since you know capitalize()
all you need is to split the string with space as a delimeter to extract each word and apply capitalize()
to each word. Then rejoin all the words.
fun String.capitalizeWords(): String = split(" ").map { it.capitalize() }.joinToString(" ")
use it:
val s = "the quick brown fox"
println(s.capitalizeWords())
will print:
The Quick Brown Fox
Note: this extension does not take in account other chars in the word which may or may not be capitalized but this does:
fun String.capitalizeWords(): String = split(" ").map { it.toLowerCase().capitalize() }.joinToString(" ")
or shorter:
@SuppressLint("DefaultLocale")
fun String.capitalizeWords(): String =
split(" ").joinToString(" ") { it.toLowerCase().capitalize() }
How to capitalize first character of each word in a string?
To capitalize all the words in a sentence, you can use re.sub
and re.findall
:
import re
def capitalize_string(s):
return re.sub('(?<=^)[a-z]|(?<=\s)[a-z]', '{}', s).format(*map(str.upper, re.findall('(?<=^)[a-z]|(?<=\s)[a-z]', s)))
strings = ['q w e r G H J K M', 'hello world lol', "1 w 2 r 3g"]
result = list(map(capitalize_string, strings))
Output:
['Q W E R G H J K M', 'Hello World Lol', '1 W 2 R 3g']
How to capitalize the first letter of a string in dart?
Since dart version 2.6, dart supports extensions:
extension StringExtension on String {
String capitalize() {
return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
}
}
So you can just call your extension like this:
import "string_extension.dart";
var someCapitalizedString = "someString".capitalize();
Return String by capitalizing every first letter of the each word and rest in lower case
I found the solution myself with same approach i started!! Here it is:
function titleCase(str) {
var strSplit = (str.split(' '));
var newLetter = [];
var firstLetter;
var restLetter;
for(i=0; i <strSplit.length; i++){
firstLetter = strSplit[i].charAt(0).toUpperCase();
restLetter = strSplit[i].slice(1, str.Split).toLowerCase();
newLetter.push(firstLetter + restLetter);
}
return newLetter.join(" ");
}
titleCase("I'm a little tea pot");
Related Topics
I'm Getting Key Error in Python
How to Create a List of Lambdas (In a List Comprehension/For Loop)
Python Recursion with List Returns None
Pandas: Multiple Conditions While Indexing Data Frame - Unexpected Behavior
How to Do Exponential and Logarithmic Curve Fitting in Python? I Found Only Polynomial Fitting
Keras Dense Layer's Input Is Not Flattened
Best Practice for Using Assert
Rank Items in an Array Using Python/Numpy, Without Sorting Array Twice
How to Execute Python Scripts in Windows
How to Read a Text File into a List or an Array with Python
From ... Import' VS 'Import .'
What Does 'Weight' Do in Tkinter
Strings in a Dataframe, But Dtype Is Object
How to Find the Exact Intersection of a Curve (As Np.Array) with Y==0
How to Extract the Decision Rules from Scikit-Learn Decision-Tree
The 'Is' Operator Behaves Unexpectedly with Non-Cached Integers