Home >Web Front-end >CSS Tutorial >How can I lowercase and then capitalize text using CSS and JavaScript?
Capitalizing Text After Lowercasing with CSS and JavaScript
It is possible to first lowercase and then capitalize text using either CSS or JavaScript.
CSS Method
CSS can be used to capitalize the first letter of each word using the text-transform property. By setting text-transform:capitalize;, text will be automatically converted to lowercase first, then the first letter of each word will be capitalized.
Example:
<code class="css">.className { text-transform: capitalize; }</code>
This CSS will ensure that all text within the element with the class className will be first loweredcase and then capitalized.
JavaScript Method
JavaScript provides a more flexible approach to capitalizing text after lowercasing. The toLowerCase() method can be used to convert all text to lowercase, followed by the replace() method to capitalize the first letter of each word.
Example:
<code class="js">function capitalize(s){ return s.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } ); }; capitalize('this IS THE wOrst string eVeR');</code>
In this example, the capitalize() function first converts the input string s to lowercase using toLowerCase(). Then, it uses the replace() method with a regular expression pattern (/b./g) to find the first letter of each word (indicated by word boundaries b), and the anonymous callback function function(a){ return a.toUpperCase(); }, capitalizes the matched letter.
The above is the detailed content of How can I lowercase and then capitalize text using CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!