Javascript equivalent for PHP's strlen

September 27, 2009
Filed under: Featured, JavaScript, Zend 

This article is part of the ‘Porting PHP to Javascript’ Project, which aims to decrease the gap between developing for PHP & Javascript.

A lot of people are familiar with PHP’s functions, and though Javascript functions are often quite similar, some functions may be missing or addressed differently. The Javascript implementations should be as compliant with the PHP versions as possible, a good indication is that the PHP function manual could also apply to the Javascript version.

Porting crucial PHP functions to Javascript can be fun & useful. Currently some PHP functions have been added, but readers are encouraged to contribute and improve functions by adding comments. Eventually the goal is to save all the functions in one php.js file and make it publicly available for your coding pleasure.

PHP strlen

Description

strlen – Get string length

int strlen( string string )

Returns the length of the given string.

Parameters

  • stringThe string being measured for length.

Return Values

The length of the string on success, and 0 if the string is empty.

See Also

Javascript strlen

Source

This is the main source of the Javascript version of PHP’s strlen

function strlen (string) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Sakimori
    // +      input by: Kirk Strobeck
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +    revised by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: May look like overkill, but in order to be truly faithful to handling all Unicode
    // %        note 1: characters and to this function in PHP which does not count the number of bytes
    // %        note 1: but counts the number of characters, something like this is really necessary.
    // *     example 1: strlen('Kevin van Zonneveld');
    // *     returns 1: 19
    // *     example 2: strlen('A\ud87e\udc04Z');
    // *     returns 2: 3

    var str = string+'';
    var i = 0, chr = '', lgth = 0;

    var getWholeChar = function (str, i) {
        var code = str.charCodeAt(i);
        var next = '', prev = '';
        if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
            if (str.length <= (i+1))  {
                throw 'High surrogate without following low surrogate';
            }
            next = str.charCodeAt(i+1);
            if (0xDC00 > next || next > 0xDFFF) {
                throw 'High surrogate without following low surrogate';
            }
            return str.charAt(i)+str.charAt(i+1);
        } else if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
            if (i === 0) {
                throw 'Low surrogate without preceding high surrogate';
            }
            prev = str.charCodeAt(i-1);
            if (0xD800 > prev || prev > 0xDBFF) { //(could change last hex to 0xDB7F to treat high private surrogates as single characters)
                throw 'Low surrogate without preceding high surrogate';
            }
            return false; // We can pass over low surrogates now as the second component in a pair which we have already processed
        }
        return str.charAt(i);
    };

    for (i=0, lgth=0; i < str.length; i++) {
        if ((chr = getWholeChar(str, i)) === false) {
            continue;
        } // Adapt this line at the top of any loop, passing in the whole string and the current iteration and returning a variable to represent the individual character; purpose is to treat the first part of a surrogate pair as the whole character and then ignore the second part
        lgth++;
    }
    return lgth;
}

Examples

Currently there are 2 examples

Example 1

This is how you could call strlen()

strlen('Kevin van Zonneveld');



And that would return

19

Example 2

This is how you could call strlen()

strlen('A\ud87e\udc04Z');

And that would return

3

More about this Project

Download php.js

To easily include it in your code, every function currently available is stored in

Normal

Namespaced What is ‘namespaced?’

To download use Right click, Save Link As
Generally the best way is to use a minified version and gzip it

More Info : click here

Comments

Tell me what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!





*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image