KOMPX.COM or COMPMISCELLANEA.COM   

Capitalize the first letter (JavaScript)

Capitalizing the first letter of a string by means of JavaScript. Two variants, using the methods:

  1. slice() + toUpperCase()
  2. replace() + toUpperCase()

1. slice() + toUpperCase()

capitalize the first letter

сделать первую букву заглавной

HTML code:


<div class="example">
	<p lang="en">capitalize the first letter</p>
	<p lang="ru">сделать первую букву заглавной</p>
</div>

JavaScript code:


<script>
var paragraphs = document.querySelectorAll('.example p');
var text = '';

for ( var paragraph of paragraphs ) {
	text = paragraph.textContent;
	paragraph.textContent = text[0].toUpperCase() + text.slice(1);
}
</script>

2. replace() + toUpperCase()

capitalize the first letter

сделать первую букву заглавной

HTML code:


<div class="example example2">
	<p lang="en">capitalize the first letter</p>
	<p lang="ru">сделать первую букву заглавной</p>
</div>

JavaScript code:


<script>
var paragraphs = document.querySelectorAll('.example2 p');
var text = '';

for ( var paragraph of paragraphs ) {
	text = paragraph.textContent;
	paragraph.textContent = text.replace( /^./, text[0].toUpperCase() );
}
</script>

Note

It works for most of the characters of most of the modern languages. But there may or will be problems with characters beyond the Basic Multilingual Plane (BMP) of Unicode, some digraphs or other language specific incompatibilities with the Latin upper-lower case characters conventions.

See the discussions on internationalization:

Browser support
Windows
Firefox 13.0+
Google Chrome 51.0+
Opera 38.0+
Linux
Firefox 13.0+
Google Chrome 51.0+
Opera 38.0+
More