Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

JavaScript - how to make first letter of string uppercase?

0 contributions
5 points

In this article, we're going to have a look at how to capitalize first letter of string in JavaScript.

Quick overview:

Note: presented below example is not universal. Read all article to find better universal solutions.

// ONLINE-RUNNER:browser;

function capitalizeTest(text) {
    return text && text[0].toUpperCase() + text.slice(1);
}

// Usage examples:

console.log(capitalizeTest('abc'));
console.log(capitalizeTest('this is text'));

Note: read this article to capitalize text with CSS.

1. Capital letter of first word examples

Presented approaches find first letter in string and transform it to upper case. To find begining of first world regular expression is used in below examples.

1.1. String replace method with regular expression example

This section shows how to capitalize first word occurrence with replace method.

// ONLINE-RUNNER:browser;

var expression = /\b\w/;

function convertSentence(text) {
  	var result = text.replace(expression, function(text) {
    	return text.toUpperCase();
    });

  	return result;
}

// Example:

var text = 'this is some sentence...';
var convertedText = convertSentence(text);

console.log(convertedText);

1.2. String search method with regular expression example

This section shows how to capitalize first word occurrence with search method.

// ONLINE-RUNNER:browser;

var expression = /\b\w/;

function convertSentence(text) {
  	var index = text.search(expression);
  
  	if(index > -1) {
        var value = text[index];

        var prefix = text.substring(0, index);
        var suffix = text.substring(index + 1);
       
        return prefix + value.toUpperCase() + suffix;
    }
  
  	return text;
}

// Example:

var text = 'this is some sentence...';
var convertedText = convertSentence(text);

console.log(convertedText);
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more