Python title method in JavaScript
What is the equivalent for the Python string title
method in JavaScript? Python’s native str.title()
method returns a string with title-casing— i.e. the first letter of each word is capitalized.
str.title()
method in JavaScript
Unfortunately, JavaScript does not contain a standardized str.title()
method; however, a function can be created that implements equivalent behavior.
In Python, here are a few examples of the str.title()
method:
1print("WeIrD cAsInG".title()) # Weird Casing
2print("HELLO WORLD".title()) # Hello World
3print("nospaceHERE".title()) # Nospacehere
4print("there's a snake in my boot".title()) # There'S A Snake In My Boot
This is an equivalent JavaScript implementation:
1function title(str) {
2 return str.toLowerCase().split(' ').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
3}
4
5console.log(title("WeIrD cAsInG")); // Weird Casing
6console.log(title("HELLO WORLD")); // Hello World
7console.log(title("nospaceHERE")); // Nospacehere
8console.log(title("there's a snake in my boot")); // There'S A Snake In My Boot