Languages
[Edit]
EN

JavaScript - make first letter of string uppercase

5 points
Created by:
Root-ssh
177620

In this article, we would like to show you how to capitalize the first letter of a string in JavaScript.

Quick solution:

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) || text;
}

// Usage examples:

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

Output:

Abc
This is text

ES6 version

// ONLINE-RUNNER:browser;

const capitalizeTest = (text) => {
    return text && text[0].toUpperCase() + text.slice(1) || text;
};

// Usage examples:

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

Output:

Abc
This is text

Note: read this article to capitalize text with CSS.

 

1. Capital letter of first-word examples

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

1.1. String replace method with regular expression example

This section shows how to capitalize first-word occurrences 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);

Output:

This is some sentence...

1.2. String search method with regular expression example

This section shows how to capitalize first-word occurrences 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);

Output:

This is some sentence...

Alternative titles

  1. How to uppercase first letter of string in JavaScript?
  2. How to capitalize first world of string in JavaScript?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join