How do I make the first letter of a string uppercase in JavaScript?

JavascriptStringLetterCapitalize

Javascript Problem Overview


How do I make the first letter of a string uppercase, but not change the case of any of the other letters?

For example:

  • "this is a test""This is a test"
  • "the Eiffel Tower""The Eiffel Tower"
  • "/index.html""/index.html"

Javascript Solutions


Solution 1 - Javascript

The basic solution is:

function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

console.log(capitalizeFirstLetter('foo')); // Foo

Some other answers modify String.prototype (this answer used to as well), but I would advise against this now due to maintainability (hard to find out where the function is being added to the prototype and could cause conflicts if other code uses the same name / a browser adds a native function with that same name in future).

...and then, there is so much more to this question when you consider internationalisation, as this astonishingly good answer (buried below) shows.

If you want to work with Unicode code points instead of code units (for example to handle Unicode characters outside of the Basic Multilingual Plane) you can leverage the fact that String#[@iterator] works with code points, and you can use toLocaleUpperCase to get locale-correct uppercasing:

const capitalizeFirstLetter = ([ first, ...rest ], locale = navigator.language) =>
  first.toLocaleUpperCase(locale) + rest.join('')

console.log(
  capitalizeFirstLetter('foo'), // Foo
  capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉"), // "𐐎𐐲𐑌𐐼𐐲𐑉" (correct!)
  capitalizeFirstLetter("italya", 'tr') // İtalya" (correct in Turkish Latin!)
)

For even more internationalization options, please see the original answer below.

Solution 2 - Javascript

Here's a more object-oriented approach:

Object.defineProperty(String.prototype, 'capitalize', {
  value: function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
  },
  enumerable: false
});

You'd call the function, like this:

"hello, world!".capitalize();

With the expected output being:

"Hello, world!"

Solution 3 - Javascript

In CSS:

p::first-letter {
    text-transform:capitalize;
}

Solution 4 - Javascript

Here is a shortened version of the popular answer that gets the first letter by treating the string as an array:

function capitalize(s)
{
    return s[0].toUpperCase() + s.slice(1);
}

Update

According to the comments below this doesn't work in IE 7 or below.

Update 2:

To avoid undefined for empty strings (see @njzk2's comment below), you can check for an empty string:

function capitalize(s)
{
    return s && s[0].toUpperCase() + s.slice(1);
}
ES version
const capitalize = s => s && s[0].toUpperCase() + s.slice(1)

// to always return type string event when s may be falsy other than empty-string
const capitalize = s => (s && s[0].toUpperCase() + s.slice(1)) || ""

Solution 5 - Javascript

If you're interested in the performance of a few different methods posted:

Here are the fastest methods based on this jsperf test (ordered from fastest to slowest).

As you can see, the first two methods are essentially comparable in terms of performance, whereas altering the String.prototype is by far the slowest in terms of performance.

// 10,889,187 operations/sec
function capitalizeFirstLetter(string) {
    return string[0].toUpperCase() + string.slice(1);
}

// 10,875,535 operations/sec
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

// 4,632,536 operations/sec
function capitalizeFirstLetter(string) {
    return string.replace(/^./, string[0].toUpperCase());
}

// 1,977,828 operations/sec
String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

enter image description here

Solution 6 - Javascript

I didn’t see any mention in the existing answers of issues related to astral plane code points or internationalization. “Uppercase” doesn’t mean the same thing in every language using a given script.

Initially I didn’t see any answers addressing issues related to astral plane code points. There is one, but it’s a bit buried (like this one will be, I guess!)


Most of the proposed functions look like this:

function capitalizeFirstLetter(str) {
  return str[0].toUpperCase() + str.slice(1);
}

However, some cased characters fall outside the BMP (basic multilingual plane, code points U+0 to U+FFFF). For example take this Deseret text:

capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉"); // "𐐶𐐲𐑌𐐼𐐲𐑉"

The first character here fails to capitalize because the array-indexed properties of strings don’t access “characters” or code points*. They access UTF-16 code units. This is true also when slicing — the index values point at code units.

It happens to be that UTF-16 code units are 1:1 with USV code points within two ranges, U+0 to U+D7FF and U+E000 to U+FFFF inclusive. Most cased characters fall into those two ranges, but not all of them.

From ES2015 on, dealing with this became a bit easier. String.prototype[@@iterator] yields strings corresponding to code points**. So for example, we can do this:

function capitalizeFirstLetter([ first, ...rest ]) {
  return [ first.toUpperCase(), ...rest ].join('');
}

capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉") // "𐐎𐐲𐑌𐐼𐐲𐑉"

For longer strings, this is probably not terribly efficient*** — we don’t really need to iterate the remainder. We could use String.prototype.codePointAt to get at that first (possible) letter, but we’d still need to determine where the slice should begin. One way to avoid iterating the remainder would be to test whether the first codepoint is outside the BMP; if it isn’t, the slice begins at 1, and if it is, the slice begins at 2.

function capitalizeFirstLetter(str) {
  const firstCP = str.codePointAt(0);
  const index = firstCP > 0xFFFF ? 2 : 1;

  return String.fromCodePoint(firstCP).toUpperCase() + str.slice(index);
}

capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉") // "𐐎𐐲𐑌𐐼𐐲𐑉"

You could use bitwise math instead of > 0xFFFF there, but it’s probably easier to understand this way and either would achieve the same thing.

We can also make this work in ES5 and below by taking that logic a bit further if necessary. There are no intrinsic methods in ES5 for working with codepoints, so we have to manually test whether the first code unit is a surrogate****:

function capitalizeFirstLetter(str) {
  var firstCodeUnit = str[0];

  if (firstCodeUnit < '\uD800' || firstCodeUnit > '\uDFFF') {
    return str[0].toUpperCase() + str.slice(1);
  }

  return str.slice(0, 2).toUpperCase() + str.slice(2);
}

capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉") // "𐐎𐐲𐑌𐐼𐐲𐑉"

At the start I also mentioned internationalization considerations. Some of these are very difficult to account for because they require knowledge not only of what language is being used, but also may require specific knowledge of the words in the language. For example, the Irish digraph "mb" capitalizes as "mB" at the start of a word. Another example, the German eszett, never begins a word (afaik), but still helps illustrate the problem. The lowercase eszett (“ß”) capitalizes to “SS,” but “SS” could lowercase to either “ß” or “ss” — you require out-of-band knowledge of the German language to know which is correct!

The most famous example of these kinds of issues, probably, is Turkish. In Turkish Latin, the capital form of i is İ, while the lowercase form of I is ı — they’re two different letters. Fortunately we do have a way to account for this:

function capitalizeFirstLetter([ first, ...rest ], locale) {
  return [ first.toLocaleUpperCase(locale), ...rest ].join('');
}

capitalizeFirstLetter("italy", "en") // "Italy"
capitalizeFirstLetter("italya", "tr") // "İtalya"

In a browser, the user’s most-preferred language tag is indicated by navigator.language, a list in order of preference is found at navigator.languages, and a given DOM element’s language can be obtained (usually) with Object(element.closest('[lang]')).lang || YOUR_DEFAULT_HERE in multilanguage documents.

In agents which support Unicode property character classes in RegExp, which were introduced in ES2018, we can clean stuff up further by directly expressing what characters we’re interested in:

function capitalizeFirstLetter(str, locale=navigator.language) {
  return str.replace(/^\p{CWU}/u, char => char.toLocaleUpperCase(locale));
}

This could be tweaked a bit to also handle capitalizing multiple words in a string with fairly good accuracy. The CWU or Changes_When_Uppercased character property matches all code points which, well, change when uppercased. We can try this out with a titlecased digraph characters like the Dutch ij for example:

capitalizeFirstLetter('ijsselmeer'); // "IJsselmeer"

As of January 2021, all major engines have implemented the Unicode property character class feature, but depending on your target support range you may not be able to use it safely yet. The last browser to introduce support was Firefox (78; June 30, 2020). You can check for support of this feature with the Kangax compat table. Babel can be used to compile RegExp literals with property references to equivalent patterns without them, but be aware that the resulting code can sometimes be enormous. You probably would not want to do this unless you’re certain the tradeoff is justified for your use case.


In all likelihood, people asking this question will not be concerned with Deseret capitalization or internationalization. But it’s good to be aware of these issues because there’s a good chance you’ll encounter them eventually even if they aren’t concerns presently. They’re not “edge” cases, or rather, they’re not by-definition edge cases — there’s a whole country where most people speak Turkish, anyway, and conflating code units with codepoints is a fairly common source of bugs (especially with regard to emoji). Both strings and language are pretty complicated!


* The code units of UTF-16 / UCS2 are also Unicode code points in the sense that e.g. U+D800 is technically a code point, but that’s not what it “means” here ... sort of ... though it gets pretty fuzzy. What the surrogates definitely are not, though, is USVs (Unicode scalar values).

** Though if a surrogate code unit is “orphaned” — i.e., not part of a logical pair — you could still get surrogates here, too.

*** maybe. I haven’t tested it. Unless you have determined capitalization is a meaningful bottleneck, I probably wouldn’t sweat it — choose whatever you believe is most clear and readable.

**** such a function might wish to test both the first and second code units instead of just the first, since it’s possible that the first unit is an orphaned surrogate. For example the input "\uD800x" would capitalize the X as-is, which may or may not be expected.

Solution 7 - Javascript

For another case I need it to capitalize the first letter and lowercase the rest. The following cases made me change this function:

//es5
function capitalize(string) {
    return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
capitalize("alfredo")  // => "Alfredo"
capitalize("Alejandro")// => "Alejandro
capitalize("ALBERTO")  // => "Alberto"
capitalize("ArMaNdO")  // => "Armando"

// es6 using destructuring 
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();

Solution 8 - Javascript

This is the 2018 ECMAScript 6+ Solution:

const str = 'the Eiffel Tower';
const newStr = `${str[0].toUpperCase()}${str.slice(1)}`;
console.log('Original String:', str); // the Eiffel Tower
console.log('New String:', newStr); // The Eiffel Tower

Solution 9 - Javascript

If you're already (or considering) using Lodash, the solution is easy:

_.upperFirst('fred');
// => 'Fred'

_.upperFirst('FRED');
// => 'FRED'

_.capitalize('fred') //=> 'Fred'

See their documentation: https://lodash.com/docs#capitalize

_.camelCase('Foo Bar'); //=> 'fooBar'

https://lodash.com/docs/4.15.0#camelCase

_.lowerFirst('Fred');
// => 'fred'

_.lowerFirst('FRED');
// => 'fRED'

_.snakeCase('Foo Bar');
// => 'foo_bar'

Vanilla JavaScript for first upper case:

function upperCaseFirst(str){
    return str.charAt(0).toUpperCase() + str.substring(1);
}

Solution 10 - Javascript

Capitalize the first letter of all words in a string:

function ucFirstAllWords( str )
{
    var pieces = str.split(" ");
    for ( var i = 0; i < pieces.length; i++ )
    {
        var j = pieces[i].charAt(0).toUpperCase();
        pieces[i] = j + pieces[i].substr(1);
    }
    return pieces.join(" ");
}

Solution 11 - Javascript

CSS only

If the transformation is needed only for displaying on a web page:

p::first-letter {
  text-transform: uppercase;
}
  • Despite being called "::first-letter", it applies to the first character, i.e. in case of string %a, this selector would apply to % and as such a would not be capitalized.
  • In IE9+ or IE5.5+ it's supported in legacy notation with only one colon (:first-letter).

ES2015 one-liner

const capitalizeFirstChar = str => str.charAt(0).toUpperCase() + str.substring(1);
Remarks
  • In the benchmark I performed, there was no significant difference between string.charAt(0) and string[0]. Note however, that string[0] would be undefined for an empty string, so the function would have to be rewritten to use "string && string[0]", which is way too verbose, compared to the alternative.
  • string.substring(1) is faster than string.slice(1).
Benchmark between substring() and slice()

The difference is rather minuscule nowadays (run the test yourself):

  • 21,580,613.15 ops/s ±1.6% for substring(),
  • 21,096,394.34 ops/s ±1.8% (2.24% slower) for slice().

Solutions' comparison

Solution 12 - Javascript

There is a very simple way to implement it by replace. For ECMAScript 6:

'foo'.replace(/^./, str => str.toUpperCase())

Result:

'Foo'

Solution 13 - Javascript

It's always better to handle these kinds of stuff using CSS first, in general, if you can solve something using CSS, go for that first, then try JavaScript to solve your problems, so in this case try using :first-letter in CSS and apply text-transform:capitalize;

So try creating a class for that, so you can use it globally, for example: .first-letter-uppercase and add something like below in your CSS:

.first-letter-uppercase:first-letter {
    text-transform:capitalize;
}

Also the alternative option is JavaScript, so the best gonna be something like this:

function capitalizeTxt(txt) {
  return txt.charAt(0).toUpperCase() + txt.slice(1); //or if you want lowercase the rest txt.slice(1).toLowerCase();
}

and call it like:

capitalizeTxt('this is a test'); // return 'This is a test'
capitalizeTxt('the Eiffel Tower'); // return 'The Eiffel Tower'
capitalizeTxt('/index.html');  // return '/index.html'
capitalizeTxt('alireza');  // return 'Alireza'
capitalizeTxt('dezfoolian');  // return 'Dezfoolian'

If you want to reuse it over and over, it's better attach it to javascript native String, so something like below:

String.prototype.capitalizeTxt = String.prototype.capitalizeTxt || function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

and call it as below:

'this is a test'.capitalizeTxt(); // return 'This is a test'
'the Eiffel Tower'.capitalizeTxt(); // return 'The Eiffel Tower'
'/index.html'.capitalizeTxt();  // return '/index.html'
'alireza'.capitalizeTxt();  // return 'Alireza'

Solution 14 - Javascript

String.prototype.capitalize = function(allWords) {
   return (allWords) ? // If all words
      this.split(' ').map(word => word.capitalize()).join(' ') : // Break down the phrase to words and then recursive
                                                                 // calls until capitalizing all words
      this.charAt(0).toUpperCase() + this.slice(1); // If allWords is undefined, capitalize only the first word,
                                                    // meaning the first character of the whole string
}

And then:

 "capitalize just the first word".capitalize(); ==> "Capitalize just the first word"
 "capitalize all words".capitalize(true); ==> "Capitalize All Words"

Update November 2016 (ES6), just for fun:

const capitalize = (string = '') => [...string].map(    // Convert to array with each item is a char of
                                                        // string by using spread operator (...)
    (char, index) => index ? char : char.toUpperCase()  // Index true means not equal 0, so (!index) is
                                                        // the first character which is capitalized by
                                                        // the `toUpperCase()` method
 ).join('')                                             // Return back to string

then capitalize("hello") // Hello

Solution 15 - Javascript

We could get the first character with one of my favorite RegExp, looks like a cute smiley: /^./

String.prototype.capitalize = function () {
  return this.replace(/^./, function (match) {
    return match.toUpperCase();
  });
};

And for all coffee-junkies:

String::capitalize = ->
  @replace /^./, (match) ->
    match.toUpperCase()

...and for all guys who think that there's a better way of doing this, without extending native prototypes:

var capitalize = function (input) {
  return input.replace(/^./, function (match) {
    return match.toUpperCase();
  });
};

Solution 16 - Javascript

SHORTEST 3 solutions, 1 and 2 handle cases when s string is "", null and undefined:

 s&&s[0].toUpperCase()+s.slice(1)        // 32 char

 s&&s.replace(/./,s[0].toUpperCase())    // 36 char - using regexp

'foo'.replace(/./,x=>x.toUpperCase())    // 31 char - direct on string, ES6

let s='foo bar';

console.log( s&&s[0].toUpperCase()+s.slice(1) );

console.log( s&&s.replace(/./,s[0].toUpperCase()) );

console.log( 'foo bar'.replace(/./,x=>x.toUpperCase()) );

Solution 17 - Javascript

Here is a function called ucfirst()(short for "upper case first letter"):

function ucfirst(str) {
    var firstLetter = str.substr(0, 1);
    return firstLetter.toUpperCase() + str.substr(1);
}

You can capitalise a string by calling ucfirst("some string") -- for example,

ucfirst("this is a test") --> "This is a test"

It works by splitting the string into two pieces. On the first line it pulls out firstLetter and then on the second line it capitalises firstLetter by calling firstLetter.toUpperCase() and joins it with the rest of the string, which is found by calling str.substr(1).

You might think this would fail for an empty string, and indeed in a language like C you would have to cater for this. However in JavaScript, when you take a substring of an empty string, you just get an empty string back.

Solution 18 - Javascript

Use:

var str = "ruby java";

console.log(str.charAt(0).toUpperCase() + str.substring(1));

It will output "Ruby java" to the console.

Solution 19 - Javascript

If you use Underscore.js or Lodash, the underscore.string library provides string extensions, including capitalize:

> _.capitalize(string) Converts first letter of the string to > uppercase.

Example:

_.capitalize("foo bar") == "Foo bar"

Solution 20 - Javascript

If you're ok with capitalizing the first letter of every word, and your usecase is in HTML, you can use the following CSS:

<style type="text/css">
    p.capitalize {text-transform:capitalize;}
</style>
<p class="capitalize">This is some text.</p>

This is from CSS text-transform Property (at W3Schools).

Solution 21 - Javascript

var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);

Solution 22 - Javascript

If you are wanting to reformat all-caps text, you might want to modify the other examples as such:

function capitalize (text) {
    return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}

This will ensure that the following text is changed:

TEST => Test
This Is A TeST => This is a test

Solution 23 - Javascript

String.prototype.capitalize = function(){
    return this.replace(/(^|\s)([a-z])/g, 
                        function(m, p1, p2) {
                            return p1 + p2.toUpperCase();
                        });
};

Usage:

capitalizedString = someString.capitalize();

This is a text string => This Is A Text String

Solution 24 - Javascript

function capitalize(s) {
    // returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
    return s[0].toUpperCase() + s.substr(1);
}


// examples
capitalize('this is a test');
=> 'This is a test'

capitalize('the Eiffel Tower');
=> 'The Eiffel Tower'

capitalize('/index.html');
=> '/index.html'

Solution 25 - Javascript

yourString.replace(/\w/, c => c.toUpperCase())

I found this arrow function easiest. Replace matches the first letter character (\w) of your string and converts it to uppercase. Nothing fancier is necessary.

Solution 26 - Javascript

var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);

Solution 27 - Javascript

헔 헦헼헹혂혁헶헼헻 헧헵헮혁 헪헼헿헸혀 헙헼헿 헔헹헹 헨헻헶헰헼헱헲 헖헵헮헿헮헰혁헲헿혀

57 81 different answers for this question, some off-topic, and yet none of them raise the important issue that none of the solutions listed will work with Asian characters, emoji's, and other high Unicode-point-value characters in many browsers. Here is a solution that will:

const consistantCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
    function(S) {
        "use-strict"; // Hooray! The browser uses UTF-32!
        return S.charAt(0).toUpperCase() + S.substring(1);
    } : function(S) {
        "use-strict";
        // The browser is using UCS16 to store UTF-16
        var code = S.charCodeAt(0)|0;
        return (
          code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
            S.slice(0,2).toUpperCase() + S.substring(2) :
            S.charAt(0).toUpperCase() + S.substring(1)
        );
    };
const prettyCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
    function(S) {
        "use-strict"; // Hooray! The browser uses UTF-32!
        return S.charAt(0).toLocaleUpperCase() + S.substring(1);
    } : function(S) {
        "use-strict";
        // The browser is using UCS16 to store UTF-16
        var code = S.charCodeAt(0)|0;
        return (
          code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
            S.slice(0,2).toLocaleUpperCase() + S.substring(2) :
            S.charAt(0).toLocaleUpperCase() + S.substring(1)
        );
    };

Do note that the above solution tries to account for UTF-32. However, the specification officially states that browsers are required to do everything in UTF-16 mapped into UCS2. Nevertheless, if we all come together, do our part, and start preparing for UTF32, then there is a chance that the TC39 may allow browsers to start using UTF-32 (like how Python uses 24-bits for each character of the string). This must seem silly to an English speaker: no one who uses only latin-1 has ever had to deal with Mojibake because Latin-I is supported by all character encodings. But, users in other countries (such as China, Japan, Indonesia, etc.) are not so fortunate. They constantly struggle with encoding problems not just from the webpage, but also from the JavaScript: many Chinese/Japanese characters are treated as two letters by JavaScript and thus may be broken apart in the middle, resulting in � and � (two question-marks that make no sense to the end user). If we could start getting ready for UTF-32, then the TC39 might just allow browsers do what Python did many years ago which had made Python very popular for working with high Unicode characters: using UTF-32.

consistantCapitalizeFirstLetter works correctly in Internet Explorer 3+ (when the const is changed to var). prettyCapitalizeFirstLetter requires Internet Explorer 5.5+ (see the top of page 250 of this document). However, these fact are more of just jokes because it is very likely that the rest of the code on your webpage will not even work in Internet Explorer 8 - because of all the DOM and JScript bugs and lack of features in these older browsers. Further, no one uses Internet Explorer 3 or Internet Explorer 5.5 any more.

Solution 28 - Javascript

Check out this solution:

var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // Returns Master

Solution 29 - Javascript

Only because this is really a one-liner I will include this answer. It's an ES6-based interpolated string one-liner.

let setStringName = 'the Eiffel Tower';
setStringName = `${setStringName[0].toUpperCase()}${setStringName.substring(1)}`;

Solution 30 - Javascript

The ucfirst function works if you do it like this.

function ucfirst(str) {
    var firstLetter = str.slice(0,1);
    return firstLetter.toUpperCase() + str.substring(1);
}

Thanks J-P for the aclaration.

Solution 31 - Javascript

yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });

(You may encapsulate it in a function or even add it to the String prototype if you use it frequently.)

Solution 32 - Javascript

You can do it in one line like this

string[0].toUpperCase() + string.substring(1)

Solution 33 - Javascript

Here's my version. I think it's easy to understand and elegant too.

var str = "foo bar baz";

// Capitalize
str.split(' ')
    .map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
    .join(' ')
// Returns "Foo Bar Baz"

// Capitalize the first letter
str.charAt(0).toUpperCase() + str.slice(1)
// Returns "Foo bar baz"

Solution 34 - Javascript

with arrow function

let fLCapital = s => s.replace(/./, c => c.toUpperCase())
fLCapital('this is a test') // "This is a test"

with arrow function, another solution

let fLCapital = s => s = s.charAt(0).toUpperCase() + s.slice(1);
fLCapital('this is a test') // "This is a test"

with array and map()

let names = ['james', 'robert', 'mary']
let makeFNLCapital = names.map(name => name.replace(/./, c => c.toUpperCase()))
makeFNLCapital // ["James", "Robert", "Mary"]

Solution 35 - Javascript

A functional approach

const capitalize = ([s, ...tring]) =>
  [s.toUpperCase(), ...tring]
    .join('');

Then you could

const titleCase = str => 
  str
    .split(' ')
    .map(capitalize)
    .join(' ')

Solution 36 - Javascript

The first character of every string is capitalized.

function capitalize(word){
    return word[0].toUpperCase() + word.slice(1).toLowerCase();
}

console.log(capitalize("john")); //John
console.log(capitalize("BRAVO")); //Bravo
console.log(capitalize("BLAne")); //Blane

Solution 37 - Javascript

CoffeeScript
ucfirst = (str) -> str.charAt(0).toUpperCase() + str.slice(1)

As a String prototype method:

String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)

Solution 38 - Javascript

In CoffeeScript, add to the prototype for a string:

String::capitalize = ->
  @substr(0, 1).toUpperCase() + @substr(1)

Usage would be:

"woobie".capitalize()

Which yields:

"Woobie"

Solution 39 - Javascript

function capitalize(string) {
    return string.replace(/^./, Function.call.bind("".toUpperCase));
}

Solution 40 - Javascript

Posting an edit of @salim's answer to include locale letter transformation.

var str = "test string";
str = str.substring(0,1).toLocaleUpperCase() + str.substring(1);

Solution 41 - Javascript

There are already so many good answers, but you can also use a simple CSS transform:

text-transform: capitalize;

div.c {
  text-transform: capitalize;
}

<h2>text-transform: capitalize:</h2>
<div class="c">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>

Solution 42 - Javascript

// Uppercase first letter
function ucfirst(field) {
    field.value = field.value.substr(0, 1).toUpperCase() + field.value.substr(1);
}

Usage:

<input type="text" onKeyup="ucfirst(this)" />

Solution 43 - Javascript

Using the JS replace string method & a regular expression w/ a word boundary seems simple.

Capitalize the first words' first character: "the eiffel tower" --> "The eiffel tower"

str.replace(/\b\w/, v => v.toUpperCase())

Capitalize all words' first character: "the eiffel tower" --> "The Eiffel Tower"

str.replace(/\b\w/g, v => v.toUpperCase())

Solution 44 - Javascript

One possible solution:

function ConvertFirstCharacterToUpperCase(text) {
    return text.substr(0, 1).toUpperCase() + text.substr(1);    
}

Use this:

 alert(ConvertFirstCharacterToUpperCase("this is string"));

Here is working JS Fiddle

Solution 45 - Javascript

This solution might be new and probably the simplest.

function firstUpperCase(input)
{
    return input[0].toUpperCase() + input.substr(1);
}

console.log(firstUpperCase("capitalize first letter"));

Solution 46 - Javascript

/*
 * As terse as possible, assuming you're using ES version 6+
 */
var upLetter1=s=>s.replace(/./,m=>m.toUpperCase());

console.log(upLetter1("the quick brown fox jumped over the lazy dog."));
//\\ The quick brown fox jumped over the lazy dog. //\\

Solution 47 - Javascript

Using an arrow function:

const capitalize = string => string[0].toUpperCase() + string.slice(1)

Solution 48 - Javascript

Here is my attempt to make a universal function that can capitalize only the first letter, or the first letter of each word, including words separated by a dash (like some first names in French).

By default, the function capitalizes only the first letter and leave the rest untouched.

Parameters:

  • lc: true to force lower-casing the rest of the word(s)
  • all: true to capitalize each word

 

if( typeof String.prototype.capitalize !== "function" ) {
    String.prototype.capitalize = function( lc, all ) {
        if( all ) {
            return this.split( " " )
                       .map( currentValue => currentValue.capitalize( lc ), this )
                       .join( " " )
                       .split( "-" )
                       .map( currentValue => currentValue.capitalize( false ), this )
                       .join( "-" );
        } else {
            return lc
            ? this.charAt( 0 ).toUpperCase() + this.slice( 1 ).toLowerCase()
            : this.charAt( 0 ).toUpperCase() + this.slice( 1 );
        }
    }
}

Solution 49 - Javascript

Or you could use Sugar.js capitalize()

Example:

'hello'.capitalize()           -> 'Hello'
'hello kitty'.capitalize()     -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'

Solution 50 - Javascript

Using prototypes

String.prototype.capitalize = function () {
    return this.charAt(0) + this.slice(1).toLowerCase();
  }

or Using functions

function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}

Solution 51 - Javascript

a.slice(0,1).toUpperCase()+a.slice(1)

let a = 'hello',
    fix = a.slice(0,1).toUpperCase()+a.slice(1)
    
console.log(fix)

Solution 52 - Javascript

There are multiple ways of doing this try some below

var lower = 'the Eiffel Tower';
var upper = lower.charAt(0).toUpperCase() + lower.substr(1);

And if you are comfortable with regular expressions, you do things this way:

var upper = lower.replace(/^\w/, function (chr) {
  return chr.toUpperCase();
});

And you can even take it one step further by using more modern syntax:

const upper = lower.replace(/^\w/, c => c.toUpperCase());

Also this will take care of negative scenarios as mentioned in example like words starting with special characters like !@#$%^&*()}{{[];':",.<>/? .

Solution 53 - Javascript

Unicode and Locale Aware

Using current language features:

function capitalize([firstLetter, ...rest]) {
  return [firstLetter.toLocaleUpperCase(), ...rest].join('');
}

console.log(capitalize('foo bar'));
console.log(capitalize('ѷҥӕ'))
console.log(capitalize('🎁❄💊🎸⭐'));

// Title Case
console.log(
  'Title Case:',
  'foo bar'
    .split(/\s+/)
    .map(capitalize)
    .join(' '),
);

We accept a destructured string as the only parameter [firstLetter, ...rest], assigning the first character to the variable firstLetter and get an array for the rest of the characters (...rest) bound to the rest variable. E.g. for the string lorem ipsum this should look like:

capitalize('lorem ipsum');
// firstLetter = 'l'
// rest = ['o', 'r', 'e', 'm', ' ', 'i', 'p', 's', 'u', 'm'];

Now all we need to do is prepend an uppercased version of the first letter firstLetter.toLocaleUpperCase() to the rest array—using the spread operator—and join the resulting array into a string using .join('')

Solution 54 - Javascript

If you go with one of the regex answers, remember they will only work with ASCII characters. All your unicode letters will not be uppercased. The XRegExp library and its unicode plugins solve this problem if you want to stick with regexps. So something like this would work:

String.prototype.capitalize = function () {
    return this.replace(XRegExp("^\\p{L}"), function ($0) { return $0.toUpperCase(); })
}

Considering that it still doesn't cover all possibilities (combined characters, see http://www.regular-expressions.info/unicode.html) it seems easier to just use the .charAt(0).toUpperCase() approach.

Solution 55 - Javascript

This code will also handle extra spaces at the start & end of the string.

let val = '  this is test ';
val = val.trim();
val = val.charAt(0).toUpperCase() + val.slice(1);
console.log("Value => ", val);

Solution 56 - Javascript

You can use regex approach :

str.replace(/(^|\s)\S/g, letter => letter.toUpperCase());

Solution 57 - Javascript

Capitalize and Uncapitalize first Char of a String.

Functions to include:

/** First Character uppercase */
function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

/** First Character lowercase */
function uncapitalize(str) {
    return str.charAt(0).toLowerCase() + str.slice(1);
}

Example1 "First Character uppercase":

alert(capitalize("hello world"));

Result: Hello world

Example 2 "First Character lowercase":

alert(uncapitalize("Hello World, today is sunny"));

Result: hello World, today is sunny

Solution 58 - Javascript

Okay, so I am new to JavaScript. I wasn't able to get the above to work for me. So I started putting it together myself. Here's my idea (about the same, different and working syntax):

String name = request.getParameter("name");
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);

Here I get the variable from a form (it also works manually):

String name = "i am a Smartypants...";
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);

Output: "I am a Smartypants...";

Solution 59 - Javascript

var capitalizeMe = "string not starting with capital"

Capitalize with substr

var capitalized = capitalizeMe.substr(0, 1).toUpperCase() + capitalizeMe.substr(1);

Solution 60 - Javascript

For just capitalizing the first letter and make the rest of the string lower case:

function capitalize(str) {
     var splittedEnter = str.split(" ");
     var capitalized;
     var capitalizedResult;
     for (var i = 0 ; i < splittedEnter.length ; i++){
         capitalized = splittedEnter[i].charAt(0).toUpperCase();
         splittedEnter[i] = capitalized + splittedEnter[i].substr(1).toLowerCase();
    }
    return splittedEnter.join(" ");
}

capitalize("tHiS wiLL be alL CapiTaLiZED.");

The result will be:

> This Will Be All Capitalized.

Solution 61 - Javascript

I would just use a regular expression:

myString = '    the quick green alligator...';
myString.trim().replace(/^\w/, (c) => c.toUpperCase());

Solution 62 - Javascript

Elegant

const capitalize = ([firstChar, ...rest]) => `${firstChar.toUpperCase()}${rest.join('')}`;

Solution 63 - Javascript

function capitalizeEachWord(str) {
    return str.replace(/\w\S*/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

document.write(capitalizeEachWord('foo BAR God bAD'));

Solution 64 - Javascript

A small improvement - every word in titlecase.

String.prototype.toTitleCase = function(){
    return this.replace(/\b(\w+)/g, function(m,p){ return p[0].toUpperCase() + p.substr(1).toLowerCase() });
}

var s = 'heLLo, wOrLD!';
console.log(s.toTitleCase()); // Hello, World!

Solution 65 - Javascript

The simplest solution is:

let yourSentence = 'it needs first letter upper case';

yourSentence.charAt(0).toUpperCase() + yourSentence.substr(1);

or:

yourSentence.charAt(0).toUpperCase() + yourSentence.slice(1);

or:

yourSentence.substr(0, 1).toUpperCase() + yourSentence.substr(1);

Solution 66 - Javascript

1. We'll be using CSS to achieve this. It can also be set from an external CSS.

<span text-transform="capitalize ">The first letter of each word becomes an upper case</span>

2. Using vanilla JavaScript, we could do:

let string = "test case"

string = string[0].toUpperCase() + string.substring(1)
//return "Test case"

Explanation:

string[0].toUpperCase(): converts the first letter in the string to upper case

string.substring(1): deletes the first letter in the string and returns the remaining characters

text-transform="capitalize": make the first letter of each word in this tag upper case. If you use 'uppercase' as the value of text-transform, every letter in the tag will be a capital letter

Solution 67 - Javascript

The function takes two arguments:

start - the start index;
length - the length of substring to capitalise

String.prototype.subUpper = function () {
    var result = this.toString();
    var start = 0;
    var length = 1;
    if (arguments.length > 0) {
        start = arguments[0];
        if (start < this.length) {
            if (arguments.length > 1) {
                length = arguments[1];
            }
            if (start + length > this.length) {
                length = this.length - start;
            }
            var startRest = start + length;
            var prefix = start > 0 ? this.substr(0, start) : String.empty;
            var sub = this.substr(start, length);
            var suffix = this.substr(startRest, this.length - startRest);
            result = prefix + sub.toUpperCase() + suffix;
        }
    }
    return result;
};

Solution 68 - Javascript

I have been trying to do same (that is; capitalize the first letter in a string while it is being typed) using jQuery. I searched all through the web for the answer but couldn't find it. However I was able to get a work around using the on() function in jQuery like so:

$("#FirstNameField").on("keydown",function(e){
    var str = $("#FirstNameField").val();
    if(str.substring()===str.substring(0,1)){
        $("#FirstNameField").val(str.substring(0,1).toUpperCase());
    } 
});

This function actually capitalizes the first letter while the data entrant is typing continuously.

Solution 69 - Javascript

I use something along these lines in my development environment, especially when working with APIs like HTTP:

Suppose you have an HTTP header in which you'd like to capitalize every initial letter in its name and add the hyphen between its constituent words. You may achieve something like that using this basic and simple routine:

'access control allow origin'
    .replace(/\b\w/g, function (match) {
        return match.toUpperCase();
    })
    .split(' ')
    .join('-');

// Output: 'Access-Control-Allow-Origin'

It is not maybe the most elegant and attractive function definition out there, but it certainly gets the job done.

Solution 70 - Javascript

Like it:

function capitalize(string,a) {
    var tempstr = string.toLowerCase();
    if (a == false || a == undefined)
        return tempstr.replace(tempstr[0], tempstr[0].toUpperCase());
    else {
        return tempstr.split(" ").map(function (i) { return i[0].toUpperCase() + i.substring(1) }).join(" ");
    }
}


capitalize('stack overflow yeah!',true)); //Stack Overflow Yeah!

capitalize('stack stack stack stack overflow yeah!'));//Stack overflow yeah!

https://jsfiddle.net/dgmLgv7b/

Solution 71 - Javascript

A one-liner:

'string'.replace(/(^[a-z])/,function (p) { return p.toUpperCase(); } )

Solution 72 - Javascript

Firstly, I just wanted to clear up what capitalize means in this context. "This String Is Capitalized" Reliable source

You can see from the example provided this is not what the OP is looking for. What it should say is "How do I make the first letter of a string uppercase" (Not capitalize string)

function ucfirst (str) {
    return typeof str != "undefined" ? (str += '', str[0].toUpperCase() + str.substr(1)) : '';
}

Explained

typeof str != "undefined" // Is str set
? // true
str += '' // Turns the string variable into a string
str[0].toUpperCase() // Get the first character and make it upper case
+ // Add
str.substr(1) // String starting from the index 1 (starts at 0)
: // false
''; // Returns an empty string

This will work with any argument or no argument at all.

undefined         === ""
""                === ""
"my string"       === "My string"
null              === "Null"
undefined         === "";
false             === "False"
0                 === "0"
true              === "True"
[]                === ""
[true,0,"",false] === "True,0,,false"

Solution 73 - Javascript

One liner ("inputString can be set to any string"):

inputString.replace(/.{1}/, inputString.charAt(0).toUpperCase())

Solution 74 - Javascript

This one is simple

const upper = lower.replace(/^\w/, c => c.toUpperCase());

Solution 75 - Javascript

Any type of string can convert --

YoUrStRiNg → Yourstring

var str = yOuRsTrING.toLowerCase(); // Output: yourstring
str.charAt(0).toUpperCase() + str.slice(1); // Output: Y + ourstring = Yourstring

Solution 76 - Javascript

You can do str.replace(str[0], str[0].toUpperCase()).

Check this example:

let str = "hello, WORLD!"
let newStr = str.replace(str[0], str[0].toUpperCase())

console.log("str: ", str)
console.log("newStr: ", newStr)

Solution 77 - Javascript

Just install and load Lodash:

import { capitalize } from "lodash";

capitalize('test') // Test

Solution 78 - Javascript

The currently voted answer is right, but it doesn't trim or check the length of the string before capitalising the first character.

String.prototype.ucfirst = function(notrim) {
	s = notrim ? this : this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');
	return s.length > 0 ? s.charAt(0).toUpperCase() + s.slice(1) : s;
}

Set the notrim argument to prevent trimming the string first:

'pizza'.ucfirst()         => 'Pizza'
'   pizza'.ucfirst()      => 'Pizza'
'   pizza'.ucfirst(true)  => '   pizza'

Solution 79 - Javascript

This does the same action:

var newStr = string.slice(0,1).toUpperCase() + string.slice(1);

Solution 80 - Javascript

Capitalize First Word: Shortest

text.replace(/(^.)/, m => m.toUpperCase())

Capitalize Each Word: Shortest

text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());

If you want to make sure the rest is in lowercase:

text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())

Solution 81 - Javascript

I know this is an old question with a lot of answers but here's my quick snippet.

const capitalize = (str) => str?.split('').map( (e, i) => i === 0 ? e.toUpperCase() : e ).join('')

Solution 82 - Javascript

This is what I use religiously:

function capitalizeMe(str, force){
    str = force ? str.toLowerCase() : str;
    return str.replace(/(\b)([a-zA-Z])/g,
        function(firstLetter){
            return firstLetter.toUpperCase();
        });
}


var firstName = capitalizeMe($firstName.val());

Solution 83 - Javascript

If there's Lodash in your project, use upperFirst.

Solution 84 - Javascript

function cap(input) {
    return input.replace(/[\.\r\n\t\:\;\?\!]\W*(\w)/g, function(match, capture) {
         // For other sentences in the text
         return match.toUpperCase();
    }).replace(/^\W*\w/, function(match, capture) {
        // For the first sentence in the text
        return match.toUpperCase();
    });;
}

var a = "hi, dear user. it is a simple test. see you later!\r\nbye";
console.log(cap(a));
// Output: Hi, dear user. It is a simple test. See you later!
// Bye

Solution 85 - Javascript

Another way using RamdaJs, the functional programming way:

firstCapital(str){
    const fn = p => R.toUpper(R.head(p)) + R.tail(p);
    return fn(str);
}

With multiple words in a string:

firstCapitalAllWords(str){
    const fn = p => R.toUpper(R.head(p)) + R.tail(p);
    return R.map(fn,R.split(' ', str)).join(' ');
}

Solution 86 - Javascript

Just because you can, doesn't mean you should, however. It requires ECMAScript 6 as the code uses array destructuring.

const capitalizeFirstLetter = s => {
  const type = typeof s;
  if (type !== "string") {
    throw new Error(`Expected string, instead received ${type}`);
  }

  const [firstChar, ...remainingChars] = s;

  return [firstChar.toUpperCase(), ...remainingChars].join("");
};

Solution 87 - Javascript

Here is the nice and cleaner version;

var str = '';
return str.replace(new RegExp('^'+str[0]+''), str[0].toUpperCase());

Results:

this is a test --> This is a test

Solution 88 - Javascript

I prefer use a solution oriented to a functional way (mapping array for example):

Array.from(str).map((letter, i) => i === 0 ? letter.toUpperCase() : letter ).join('');

Solution 89 - Javascript

The method will take a value and then split it to have an array of string.

const firstLetterToUpperCase = value => {
 return value.replace(
    value.split("")["0"], // Split stirng and get the first letter 
    value
        .split("")
        ["0"].toString()
        .toUpperCase() // Split string and get the first letter to replace it with an uppercase value
  );
};

Solution 90 - Javascript

If you need to have all words starting with a capital letter, you can use the following function:

const capitalLetters = (s) => {
	return s.trim().split(" ").map(i => i[0].toUpperCase() + i.substr(1)).reduce((ac, i) => `${ac} ${i}`);
}

Example:

console.log(`result: ${capitalLetters("this is a test")}`)
// Result: "This Is A Test"

Solution 91 - Javascript

Capitalizing the first letter with validation

function capitalizeFirstLetter(str) {
    return (str && typeof str === 'string') ? (str.charAt(0).toUpperCase() + str.slice(1)) : "";
}

Testing

console.log(capitalizeFirstLetter(0)); // Output: ""
console.log(capitalizeFirstLetter(null)); // Output: ""
console.log(capitalizeFirstLetter("test")); // Output: "Test"
console.log(capitalizeFirstLetter({})); // Output: ""

Solution 92 - Javascript

You should do like that:

let text = "lower case";
text = text.charAt(0).toUpperCase() + text.substring(1, text.length);

Solution 93 - Javascript

Use this module of Node.js, the http://stringjs.com/ package, to capitalize your string:

var S = require('string');
S('jon').capitalize().s; //'Jon'
S('JP').capitalize().s; //'Jp'

Solution 94 - Javascript

This one will tolerate possible leading whitespaces and will not miss the target of the first letter in a string. Therefore, it might improve already good solutions available on the thread.

str = "   the Eifel Tower";
str.replace(/\w/, str.match(/\w/)[0].toUpperCase());
>> "   The Eifel Tower";

!But, will cause a 'soft' error if executed against a blank string. To avoid this possible error or unnecessary processing of a blank string or a number, a ternary conditional guarding can be used:

+str!=+str ?  str.replace(/\w/, str.match(/\w/)[0].toUpperCase()) : str;

Solution 95 - Javascript

Try this code:

alert("hello".substr(0, 1).toUpperCase() + "hello".substr(1));

It is taking the first character in "hello", capitalizing it and adding the rest of it on.

Solution 96 - Javascript

var a = "this is a test"
console.log(a.replace(/^[a-z]/g, txt => txt.toUpperCase()));

Solution 97 - Javascript

You can do something like this:

mode =  "string";
string = mode.charAt(0).toUpperCase() + mode.substr(1,mode.length).toLowerCase();
console.log(string);

This will print

String

Solution 98 - Javascript

Well, all the answers will crash if the method is passed with some unexpected type of data such as Object or function.

So to ensure that it will not crash in any conditions we'll need to check for types.

capitalizeFirstLetter = string => {
  if (typeof string == "string") {
      console.log("passed");
    return string.charAt(0).toUpperCase() + string.slice(1);
  } else {
    console.log("error");
    return string;
  }
};

//type function
console.log(
  capitalizeFirstLetter(() => {
    return true;
  })
);
// error
//  () => { return true; }

//type object
console.log(capitalizeFirstLetter({ x: 1 }));
// error
// Object { x: 1 }

//type boolean
console.log(capitalizeFirstLetter(true));
// error
// true

//type undefined
console.log(capitalizeFirstLetter(undefined));
// error
// undefined

//type null
console.log(capitalizeFirstLetter(null));
// error
// null

//type NaN
console.log(capitalizeFirstLetter(NaN));
// error
// NaN

//type number
console.log(capitalizeFirstLetter(2));
// error
// 2

//type any for e.g. class
class Jaydeep {}
console.log(capitalizeFirstLetter(new Jaydeep()));
// error
// Object {}

//type string
console.log(capitalizeFirstLetter("1"));
console.log(capitalizeFirstLetter("a"));
console.log(capitalizeFirstLetter("@"));
console.log(capitalizeFirstLetter(""));
// 1
// A
// @
//  :empty string

Solution 99 - Javascript

string = string.replace(string.charAt(0), string.charAt(0).toUpperCase());

Solution 100 - Javascript

Try with the following function:

function capitalize (string) {
  return [].map.call(string, (char, i) => i ? char : char.toUpperCase()).join('')
}

Usage:

capitalize('hello, world!')

Result:

Hello, world!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobert WillsView Question on Stackoverflow
Solution 1 - JavascriptSteve HarrisonView Answer on Stackoverflow
Solution 2 - JavascriptSteve HansellView Answer on Stackoverflow
Solution 3 - Javascriptsam6berView Answer on Stackoverflow
Solution 4 - JavascriptjoelvhView Answer on Stackoverflow
Solution 5 - JavascriptJosh CrozierView Answer on Stackoverflow
Solution 6 - JavascriptSemicolonView Answer on Stackoverflow
Solution 7 - JavascriptalejandroView Answer on Stackoverflow
Solution 8 - JavascriptSterling BourneView Answer on Stackoverflow
Solution 9 - JavascriptchovyView Answer on Stackoverflow
Solution 10 - JavascriptDanView Answer on Stackoverflow
Solution 11 - JavascriptPrzemekView Answer on Stackoverflow
Solution 12 - JavascriptLittle RoysView Answer on Stackoverflow
Solution 13 - JavascriptAlirezaView Answer on Stackoverflow
Solution 14 - JavascriptAbdennour TOUMIView Answer on Stackoverflow
Solution 15 - JavascriptyckartView Answer on Stackoverflow
Solution 16 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 17 - JavascriptRobert WillsView Answer on Stackoverflow
Solution 18 - JavascriptAMIC MINGView Answer on Stackoverflow
Solution 19 - JavascriptandershView Answer on Stackoverflow
Solution 20 - JavascriptRyanView Answer on Stackoverflow
Solution 21 - JavascriptzianwarView Answer on Stackoverflow
Solution 22 - JavascriptmonokromeView Answer on Stackoverflow
Solution 23 - JavascriptMurat KucukosmanView Answer on Stackoverflow
Solution 24 - JavascriptFredrik A.View Answer on Stackoverflow
Solution 25 - JavascriptWolfView Answer on Stackoverflow
Solution 26 - JavascriptMaxEchoView Answer on Stackoverflow
Solution 27 - JavascriptJack GView Answer on Stackoverflow
Solution 28 - JavascriptRaju BeraView Answer on Stackoverflow
Solution 29 - JavascriptChristian MatthewView Answer on Stackoverflow
Solution 30 - JavascriptraphieView Answer on Stackoverflow
Solution 31 - JavascriptSimonView Answer on Stackoverflow
Solution 32 - JavascriptQwertyView Answer on Stackoverflow
Solution 33 - Javascripta8mView Answer on Stackoverflow
Solution 34 - JavascriptAhmad MoghaziView Answer on Stackoverflow
Solution 35 - JavascriptBenny PowersView Answer on Stackoverflow
Solution 36 - JavascriptOmar bakhshView Answer on Stackoverflow
Solution 37 - JavascriptŁukasz KurowskiView Answer on Stackoverflow
Solution 38 - JavascriptlongdaView Answer on Stackoverflow
Solution 39 - JavascriptNicolòView Answer on Stackoverflow
Solution 40 - JavascriptilterView Answer on Stackoverflow
Solution 41 - JavascriptDeen JohnView Answer on Stackoverflow
Solution 42 - JavascriptPnobutsView Answer on Stackoverflow
Solution 43 - JavascriptTimView Answer on Stackoverflow
Solution 44 - JavascriptZaheer AhmedView Answer on Stackoverflow
Solution 45 - JavascriptBILAL AHMADView Answer on Stackoverflow
Solution 46 - JavascriptSapphire_BrickView Answer on Stackoverflow
Solution 47 - JavascriptgiovaniZanettiView Answer on Stackoverflow
Solution 48 - JavascriptGabriel HautclocqView Answer on Stackoverflow
Solution 49 - JavascriptandershView Answer on Stackoverflow
Solution 50 - JavascriptdaronwolffView Answer on Stackoverflow
Solution 51 - JavascriptThieliciousView Answer on Stackoverflow
Solution 52 - JavascriptMradul PandeyView Answer on Stackoverflow
Solution 53 - JavascriptRúnar BergView Answer on Stackoverflow
Solution 54 - JavascriptJakub JanuszkiewiczView Answer on Stackoverflow
Solution 55 - JavascriptDevendra KumbhkarView Answer on Stackoverflow
Solution 56 - JavascriptH.MustafaView Answer on Stackoverflow
Solution 57 - JavascriptKonstantin XFlash StratigenasView Answer on Stackoverflow
Solution 58 - JavascriptAlexView Answer on Stackoverflow
Solution 59 - JavascriptAsad FidaView Answer on Stackoverflow
Solution 60 - JavascriptHadnazzarView Answer on Stackoverflow
Solution 61 - JavascriptAbdulmoiz AhmerView Answer on Stackoverflow
Solution 62 - JavascriptManuel del PozoView Answer on Stackoverflow
Solution 63 - JavascriptEduardo CuomoView Answer on Stackoverflow
Solution 64 - JavascriptTimur UsmanovView Answer on Stackoverflow
Solution 65 - JavascriptJackkobecView Answer on Stackoverflow
Solution 66 - JavascriptChukwuEmekaView Answer on Stackoverflow
Solution 67 - JavascriptBerezhView Answer on Stackoverflow
Solution 68 - Javascriptuser28864View Answer on Stackoverflow
Solution 69 - JavascriptMr. XView Answer on Stackoverflow
Solution 70 - JavascriptISFOView Answer on Stackoverflow
Solution 71 - JavascriptszanataView Answer on Stackoverflow
Solution 72 - JavascriptTarranJonesView Answer on Stackoverflow
Solution 73 - JavascriptAditya JoshiView Answer on Stackoverflow
Solution 74 - JavascriptvictorhazbunView Answer on Stackoverflow
Solution 75 - JavascriptOmkesh SajjanwarView Answer on Stackoverflow
Solution 76 - JavascriptDory DanielView Answer on Stackoverflow
Solution 77 - JavascriptDiaMaBoView Answer on Stackoverflow
Solution 78 - JavascriptpizzamonsterView Answer on Stackoverflow
Solution 79 - JavascriptIrfan SyedView Answer on Stackoverflow
Solution 80 - JavascriptchickensView Answer on Stackoverflow
Solution 81 - JavascriptFaisal NadeemView Answer on Stackoverflow
Solution 82 - JavascriptkaleazyView Answer on Stackoverflow
Solution 83 - JavascriptmedikView Answer on Stackoverflow
Solution 84 - JavascriptSalmanAAView Answer on Stackoverflow
Solution 85 - JavascriptAbhishek MauryaView Answer on Stackoverflow
Solution 86 - JavascriptpuiuView Answer on Stackoverflow
Solution 87 - JavascriptShivam GuptaView Answer on Stackoverflow
Solution 88 - JavascriptalejokoView Answer on Stackoverflow
Solution 89 - JavascriptMohamed Ben HartouzView Answer on Stackoverflow
Solution 90 - JavascriptRuslan KorkinView Answer on Stackoverflow
Solution 91 - JavascriptSatheezView Answer on Stackoverflow
Solution 92 - JavascriptTeymurView Answer on Stackoverflow
Solution 93 - JavascriptmfqView Answer on Stackoverflow
Solution 94 - JavascriptBekim BacajView Answer on Stackoverflow
Solution 95 - Javascriptuser8903269View Answer on Stackoverflow
Solution 96 - JavascriptRambabu BommisettiView Answer on Stackoverflow
Solution 97 - JavascriptIlyas karimView Answer on Stackoverflow
Solution 98 - JavascriptJaydeep GalaniView Answer on Stackoverflow
Solution 99 - JavascriptjustcantView Answer on Stackoverflow
Solution 100 - JavascriptwhereisanddyView Answer on Stackoverflow