Use PHP functions in JavaScript

JavaScript ucfirst

Makes a string's first character uppercase

1
2
3
4
56
7
8
9
1011
12
13
14
function ucfirst (str) {
    // Makes a string's first character uppercase  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/ucfirst    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: ucfirst('kevin van zonneveld');
    // *     returns 1: 'Kevin van zonneveld'    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}
external links: original PHP docs | raw js source

Examples

Running

1
ucfirst('kevin van zonneveld');

Should return

1
'Kevin van zonneveld'

Dependencies

No dependencies, you can use this function standalone.

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have ucfirst goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Kevin van Zonneveld
13 Jan '09 Permalink

q  @ Brett Zamir: Beautiful man. If you keep this pace you may even beat Onno ;)

Hm, wrong page, but strange that your previous post didn't come through. There is nothing in my spamfilter. Maybe you had different tabs open, so that captcha didn't match (there's one valid per session), and you closed the tab without noticing. Happened to me once :)

Gravatar
Brett Zamir
12 Jan '09 Permalink

q   Here's lcfirst... It looks like you don't need the 2nd argument to substr (also in ucfirst) when you are extracting to the end...

1
2
3
4
56
7
8
9
10
function lcfirst( str ) {
    // http://kevin.vanzonneveld.net
    // *     example 1: lcfirst('Kevin Van Zonneveld');
    // *     returns 1: 'kevin Van Zonneveld'
     str += '';
    var f = str.charAt(0).toLowerCase();
    return f + str.substr(1);
}
alert(lcfirst('Kevin Van Zonneveld'))


and here's strcspn (for measuring the length of continuous sentences spoken by guests on C-SPAN):

1
2
3
4
56
7
8
9
1011
12
13
14
function strcspn (str, mask, start, length) {
    start = start ? start : 0;
    var count = (length && ((start + length) < str.length)) ? start + length : str.length;
    strct:
    for (var i=start, lgth=0; i < count; i++) {        for (var j=0; j < mask.length; j++) {
            if (str[i].indexOf(mask[j]) !== -1) {
                continue strct;
            }
        }        ++lgth;
    }
    return lgth;
}


Contribute a New function