3

Can some please suggest how to capitalize the first letter in a string (using jQuery) with

a. 'letters & numbers'
or
b. 'only letters'

example:

1. Convert from '50newyork' to '50Newyork'
2. Convert from 'paris84' to 'Paris84'
3. Convert from 'london' to 'London'

I looked at various examples on SO with no success.

SpaceX
  • 2,814
  • 2
  • 42
  • 68
  • 1
    how about a sentence like "hello everyone."? do you want it to be "Hello Everyone" or "Hello everyone"? – yaoxing Mar 22 '14 at 10:39
  • This looks like what you're looking for: http://stackoverflow.com/a/14688341/2040509 – MarioD Mar 22 '14 at 10:39

1 Answers1

6

Use the replace method:

function cap(str) {
    return str.replace(/([a-z])/, function (match, value) {
        return value.toUpperCase();
    })
}

DEMO

Edit: In case you have a string containing multiple (space-separated) words, try something like:

function cap(str) {
    return str.split(' ').map(function (e) {
        return e.replace(/([a-z])/, function (match, value) {
            return value.toUpperCase();
        })
    }).join(' ');
}

This would convert "50newyork paris84 london" to "50Newyork Paris84 London"

DEMO

tewathia
  • 6,890
  • 3
  • 22
  • 27
  • It works perfectly, I really wished to convert a string from a. '50NewyOrk' to '50Newyork', b. 'lonDon' to 'London' as well.. – SpaceX Mar 22 '14 at 10:49