100

I have searched over the web and I can't find anything to help me. I want to make the first letter of each word upper case within a variable.

So far I have tried:

toUpperCase();

And I didn't have any luck, as it uppercases all letters.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ryryan
  • 3,890
  • 13
  • 43
  • 72

27 Answers27

256

Use the .replace function to replace the lowercase letters that begin a word with the capital letter.

var str = "hello, world!";
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
});
alert(str); //Displays "Hello, World!"

If you are dealing with word characters other than just a-z, then the following (more complicated) regular expression might better suit your purposes.

var str = "петр данилович björn über ñaque αλφα";
str = str.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) {
    return letter.toUpperCase();
});
alert(str); //Displays "Петр Данилович Björn Über Ñaque Αλφα"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
  • 1
    This doesn't work with names like `Björn Lüchinger`, this becomes `BjöRn LüChinger`. Any fix for this? – Dediqated Jul 11 '14 at 08:36
  • Works great! Any hints on what the modification should be if I just wanted to convert to uppercase the first character of the string? (instead of every single word) – Andres SK Jun 22 '17 at 07:06
  • 7
    @andufo Sure, that's actually much simpler to do. Just use `str[0].toUpperCase() + str.slice(1)` – Peter Olson Jun 22 '17 at 14:05
  • @PeterOlson thanks for the answer! I ended using `var first = str.slice(0, str.indexOf(' ')); str = first.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) { return letter.toUpperCase(); }) + str.substr(first.length);` to cover special characters as well. – Andres SK Jun 22 '17 at 16:02
  • This solution make uppercase in the middle become lowercase, eg: `GNU's not unix` it will produce `Gnu's Not Unix` – Adam Mudianto Nov 02 '20 at 03:58
80

A much easier way:

$('#test').css('textTransform', 'capitalize');

I have to give Rafael Herscovici some credit for leading me down the right path. It is far simpler than whatever you guys are proposing.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vbullinger
  • 4,016
  • 3
  • 27
  • 32
33

http://phpjs.org/functions/ucwords:569 has a good example

function ucwords (str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}

(omitted function comment from source for brevity. please see linked source for details)

EDIT: Please note that this function uppercases the first letter of each word (as your question asks) and not just the first letter of a string (as your question title asks)

Jonathan Fingland
  • 56,385
  • 11
  • 85
  • 79
  • This works better than the accepted one solution that capitalizes words in a sentence after apostrophe, so e.g. "I'm an example" becomes "I'M An Example" – lizardhr Mar 04 '17 at 11:48
  • Does not work if you have an underscore in your original string, please add it to your REGEX for better performance. TY – Ruslan Abuzant Mar 30 '17 at 14:15
  • 1
    @RuslanAbuzant That would be answering a different question. Interpreting an underscore as a word separator(or general blank space) is fine, but isn't what OP was asking for... and might even break his use case. – Jonathan Fingland Apr 12 '17 at 02:35
  • 1
    ucwords() sucks. It doesn't works with Unicode (particularly with cyrillic, greek and other central European alphabets). Better use mb_convert_case() on back-end, eg: mb_convert_case($_POST['name'], MB_CASE_TITLE, 'utf-8'); – Aleksey Kuznetsov Aug 22 '19 at 11:26
17

Here is a pure JavaScript solution (no jQuery):

function capitalize(str) {
  strVal = '';
  str = str.split(' ');
  for (var chr = 0; chr < str.length; chr++) {
    strVal += str[chr].substring(0, 1).toUpperCase() + str[chr].substring(1, str[chr].length) + ' '
  }
  return strVal
}

console.log(capitalize('hello world'));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rafael Herscovici
  • 16,558
  • 19
  • 65
  • 93
14

I imagine you could use substring() and toUpperCase() to pull out the first character, uppercase it, and then replace the first character of your string with the result.

myString = "cheeseburger";
firstChar = myString.substring( 0, 1 ); // == "c"
firstChar.toUpperCase();
tail = myString.substring( 1 ); // == "heeseburger"
myString = firstChar + tail; // myString == "Cheeseburger"

I think that should work for you. Another thing to consider is that if this data is being displayed, you can add a class to its container that has the CSS property "text-transform: capitalize".

Fudgie
  • 413
  • 3
  • 12
  • shouldn't there be like firstChar = firstChar.toUpperCase(); ? I tried the code in Node.js and I had to do that or nothing changed! – Ariam1 Sep 04 '17 at 19:15
10

To do this, you don't really even need JavaScript if you're going to use

$('#test').css('text-transform', 'capitalize');

Do this as CSS like:

#test,h1,h2,h3 { text-transform: capitalize; }

Or do it as a class and apply that class to wherever you need it:

.ucwords { text-transform: capitalize; }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bruce Smith
  • 811
  • 8
  • 14
  • 5
    Welcome to Stackoverflow. Your answer is suggesting an alternative (that might be perfectly valid in some use cases), but does not really answer the question. As I understood the question, the author wanted to actually transform the Javascript variable, and not just it's visual representation. – helmbert Jan 29 '13 at 16:01
  • 4
    Yeah, but other people who come to this question might be okay with javascript OR css answers, like me, and this was really helpful... – Brian Powell Nov 17 '16 at 18:04
10

It is as simple as the following:

string = 'test';
newString = string[0].toUpperCase() + string.slice(1);
alert(newString);
Sol
  • 710
  • 8
  • 13
7

Ever heard of substr()?

For a starter:

$("#test").text($("#test").text().substr(0,1).toUpperCase()+$("#test").text().substr(1,$("#test").text().length));

Thanks to @FelixKling for the tip:

$("#test").text(function(i, text) {
    return text.substr(0,1).toUpperCase() + text.substr(1);
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cypher
  • 258
  • 2
  • 7
  • 4
    Instead of calling the `text()` **four** times, pass a function to `text()`: `$("#test").text(function(i, text) { return text.substr(0,1).toUpperCase()+text.substr(1);});` – Felix Kling Feb 26 '11 at 18:22
  • 1
    digging up old corps here, but if it was known the content goes into an element, it would be much easier to use: `$('#test').style.textTransform='capitalize';` – Rafael Herscovici Sep 24 '12 at 17:56
  • Close, @Dementic, but it should be: `$('#test').css('textTransform', 'capitalize');` BTW, this is the best answer here. I'll submit it as an answer. – vbullinger Oct 04 '12 at 19:56
  • @vbullinger - dont judge my code when i write it drunk as hell :) and i love js, not jq, so my code is wrong, but not too much `document.getElementById('test').style.textTransform='capitalize';` – Rafael Herscovici Oct 04 '12 at 21:21
6

Building on Peter Olson's answer, I took a more object-oriented approach without jQuery:

String.prototype.ucwords = function() {
    return this.toLowerCase().replace(/\b[a-z]/g, function(letter) {
        return letter.toUpperCase();
    });
}

alert("hello, world!".ucwords()); // Displays "Hello, World!"

Example: http://jsfiddle.net/LzaYH/1/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mmalone
  • 1,122
  • 9
  • 10
  • 1
    This is really the most proper way, in my opinion. I would call it `toUpperCaseWords` in keeping in line with javascript's `toUpperCase()` and `toLowerCase()` – A.B. Carroll Sep 05 '18 at 19:21
5

The simplest way

let str = "hiren raiyani"
str.toLowerCase().replace(/(?<= )[^\s]|^./g, a => a.toUpperCase());

User-defined function:

function capitalize(str){
    return str.toLowerCase().replace(/(?<= )[^\s]|^./g, a => a.toUpperCase());
}

Output: Hiren Raiyani

Use code as your user-defined function or direct.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hiren Raiyani
  • 754
  • 2
  • 12
  • 28
4
var mystring = "hello World"
mystring = mystring.substring(0,1).toUpperCase() + 
mystring.substring(1,mystring.length)

console.log(mystring) //gives you Hello World
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
3
var ar = 'foo bar spam egg'.split(/\W/);
for(var i=0; i<ar.length; i++) {
  ar[i] = ar[i].substr(0,1).toUpperCase() + ar[i].substr(1,ar[i].length-1) 
}
ar.join(' '); // Foo Bar Spam Egg
erickb
  • 6,193
  • 4
  • 24
  • 19
3

You can try this simple code with the features of ucwords in PHP.

function ucWords(text) {
    return text.split(' ').map((txt) => (txt.substring(0, 1).toUpperCase() + txt.substring(1, txt.length))).join(' ');
}
ucWords('hello WORLD');

It will keep the Upper Cases unchanged.

IamMHussain
  • 716
  • 8
  • 11
2

Based completely on Rafael Herscovici's answer, this solution is ready to call with a simple jQuery method, 'ucwords'...

$.extend({
    ucwords : function(str) {
        strVal = '';
        str = str.split(' ');
        for (var chr = 0; chr < str.length; chr++) {
            strVal += str[chr].substring(0, 1).toUpperCase() + str[chr].substring(1, str[chr].length) + ' '
        }
        return strVal
    }
});

Example:

This can be called using the method

var string = "this is a test";
string = $.ucwords(string); // Returns "This Is A Test"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JoomGuy
  • 441
  • 3
  • 7
2

You can use text-transform: capitalize; for this work.

HTML

<input type="text" style="text-transform: capitalize;" />

jQuery

$(document).ready(function (){
    var asdf = "WERTY UIOP";
    $('input').val(asdf.toLowerCase());
});

Try This

Note: It's only changing the visual representation of the string. If you alert() this string, it will always show the original value of the string.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ishan Jain
  • 8,063
  • 9
  • 48
  • 75
2

Use the below function:

const capitalize = (s) => {
  if (typeof s !== 'string')
    return ''
  return s.charAt(0).toUpperCase() + s.slice(1)
}

capitalize('test') // 'Test'
capitalize('name') // 'Name'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jignesh Patel
  • 166
  • 11
1

Without JQuery

String.prototype.ucwords = function() {
    str = this.trim();
    return str.replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g, function(s){
        return s.toUpperCase();
    });
};

console.log('hello world'.ucwords()); // Display Hello World
1

The easiest way to uppercase the first letter in JavaScript

var string = "made in india";

string = string.toLowerCase().replace(/\b[a-z]/g, function(letter){return letter.toUpperCase();});

alert(string);

Result:

"Made In India"

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Love Kumar
  • 1,056
  • 9
  • 10
1

There sure are a lot of ways to do this!

One thing that I think people forget is that strings are arrays of characters. So, the first letter of any string will be the 'zeroth' element of its array:

let word = 'interesting';
console.log(word[0]);
// 'i'

The simplest way to take advantage of this fact for the purpose of uppercasing the first letter (afaik) would be:

let word = 'interesting';
let titleCase = word[0].toUpperCase() + word.substr(1);
console.log(titleCase);
// 'Interesting'

...or as a function:

function toTitleCase(word) {
    return word[0].toUpperCase() + word.substr(1);
}
mpemburn
  • 2,776
  • 1
  • 35
  • 41
  • The first in all answers that has a decent explaination and ANSWERS THE QUESTION. The question was about making sure that the first letter in a variable is uppercase. So NOT CSS solutions and NOT uppercase every word. Where the H*LL are the moderators??? – JPA Mar 08 '23 at 16:40
1

Short and simple answer:

let str = 'this is a string';

let result = str.replace(/\b\w/g, x => x.toUpperCase());

console.log(result); // This Is A String
webHasan
  • 461
  • 3
  • 11
0

The string to lower before capitalizing the first letter.

(Both use jQuery syntax)

function CapitaliseFirstLetter(elementId) {
    var txt = $("#" + elementId).val().toLowerCase();
    $("#" + elementId).val(txt.replace(/^(.)|\s(.)/g, function($1) {
        return $1.toUpperCase();
    }));
}

In addition a function to Capitalise the WHOLE string:

function CapitaliseAllText(elementId) {
    var txt = $("#" + elementId).val();
    $("#" + elementId).val(txt.toUpperCase());
}

Syntax to use on a textbox's click event:

onClick="CapitaliseFirstLetter('TextId'); return false"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rubyist
  • 6,486
  • 10
  • 51
  • 86
0

I have used this code -

function ucword(str){
    str = str.toLowerCase().replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g, function(replace_latter) { 
        return replace_latter.toUpperCase();
    });  //Can use also /\b[a-z]/g
    return str;  //First letter capital in each word
}

var uc = ucword("good morning. how are you?");
alert(uc);
Chinmay235
  • 3,236
  • 8
  • 62
  • 93
0

HTML:

<input class="capitalize" name="Address" type="text" value="" />

JavaScript with jQuery:

$(".capitalize").bind("keyup change", function (e) {
    if ($(this).val().length == 1)
        $(this).val($(this).val().toUpperCase());
    $(this).val($(this).val().toLowerCase().replace(/\s[\p{L}a-z]/g, function (letter) {
        return letter.toUpperCase();
    }))
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Robert Benyi
  • 1,623
  • 1
  • 14
  • 10
0

var str = "HELLO WORLD HELLO WORLD HELLO WORLD HELLO WORLD";
str = str.replace(
        /([A-Z])([A-Z]+)/g,
        function (a, w1, w2) {
            return w1 + w2.toLowerCase();
        });
alert(str);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rock
  • 534
  • 6
  • 14
0

Here is Unicode-safe ucwords() function, which additionally respects double-lastnames like Russian Засс-Ранцев and some noble names like Honoré de Balzac, d'Artagnan, Vincent van Gogh, Otto von Bismarck, Sulaymān ibn Dāwūd, etc.:

String.prototype.ucwords = function() {
  return this.toLowerCase()
    .replace(/(^|\s|\-)[^\s$]/g, function(m) {
       return m.toUpperCase();
    })
    // French, Arabic and some noble names...
    .replace(/\s(Of|De|Van|Von|Ibn|Из|Ван|Фон|Ибн)\s/g, function(m) { // Honoré de Balzac, Vincent van Gogh, Otto von Bismarck, Sulaymān ibn Dāwūd etc.
       return m.toLowerCase();
    })
    .replace(/(^|\s)(D|Д)(['’][^\s$])/g, function(m, p1, p2, p3) { // D'Artagnan or d'Artagnan / Д’Артаньян или д’Артаньян
       return p1 + (p1 === "" ? p2/*.toUpperCase()*/ : p2.toLowerCase()) + p3.toUpperCase();
    });
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0
var country = $('#country').val();

var con = country[0].toUpperCase();

ctr = country.replace(country[0], con);

There isn't any need to create any function, just jugaaar.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shahid
  • 1
0

I think, the method should not convert any other letters than just the very first or the very first of any letter.

My solution for that are the following regexes:

function capitalize( str ){
    return str.replace(/^\w/, (s) => s.toUpperCase() );
}

function capitalizeAll( str ){
    return str.replace(/(\b\w)/g, (s) => s.toUpperCase() );
}

let test = 'hello world';

capitalize( test ); // Hello world
capitalizeAll( test ); // Hello World
Moritz
  • 249
  • 2
  • 11