Languages
[Edit]
EN

JavaScript - how to make first letter of string uppercase?

5 points
Created by:
Root-ssh
6417

In this article, we're going to have a look at how to capitalize first letter of 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'));

 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'));

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);
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.