forEach

Invokes a function for each UTF-16 code unit in a string.

Usage

var forEach = require( '@stdlib/string/base/for-each' );

forEach( str, clbk[, thisArg ] )

Invokes a function for each UTF-16 code unit in a string.

function log( value, index ) {
    console.log( '%d: %s', index, value );
}

forEach( 'Beep!', log );
/* =>
    0: B
    1: e
    2: e
    3: p
    4: !
*/

The invoked function is provided three arguments:

  • value: character.
  • index: character index.
  • str: input string.

To set the function execution context, provide a thisArg.

function clbk() {
    this.count += 1;
}

var str = '👉🏿';

var ctx = {
    'count': 0
};

forEach( str, clbk, ctx );

var cnt = ctx.count;
// returns 4

Examples

var forEach = require( '@stdlib/string/base/for-each' );

function log( value, index ) {
    console.log( '%d: %s', index, value );
}

forEach( 'presidential election', log );
forEach( 'Iñtërnâtiônàlizætiøn', log );
forEach( '🌷🍕', log );
forEach( '\uD834\uDD1E', log );
Did you find this page helpful?