Home  >  Article  >  Web Front-end  >  Can You Capitalize Text After Lowercasing It with CSS?

Can You Capitalize Text After Lowercasing It with CSS?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 09:08:01255browse

Can You Capitalize Text After Lowercasing It with CSS?

Capitalize Text After Lowercasing with CSS

Question: Is it possible to first lowercase text and then capitalize it using CSS?

Example:

  • HELLO WORLD → Hello World

Additional Context: You have a list of countries in uppercase (e.g., UNITED KINGDOM) and need to convert them to lowercase (e.g., United Kingdom).

Answer:

Yes, CSS provides a solution for this task:

<code class="css">.className {
  text-transform: capitalize;
}</code>

This CSS applies the text-transform: capitalize property to the element with the class className, automatically converting all lowercase letters to uppercase and the first letter of each word to lowercase.

Alternative Solution Using JavaScript:

If CSS is not an option, you can use JavaScript to achieve the same result:

<code class="javascript">function capitalize(s) {
  return s.toLowerCase().replace(/\b./g, function (a) {
    return a.toUpperCase();
  });
}

capitalize('this IS THE wOrst string eVeR');</code>

The capitalize function takes a string s as input, converts it to lowercase using toLowerCase(), and then uses the replace method with a regular expression to replace all word boundaries (b) with their uppercase equivalents. This effectively capitalizes the first letter of each word while lowercasing the rest.

The above is the detailed content of Can You Capitalize Text After Lowercasing It with CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn