Mask - javascript Mask

1

I was transcribing some functions that I have in PHP for javascript. How could I make this code more efficient?

String.prototype.substrCount = function(str){
    if(str == undefined){
        return 0;
    }
    var r = new RegExp(str, 'g');
    return (this.match(r) || []).length;
}

String.prototype.mask = function(mask){
    var value = onlyNumber(this);   // REMOVE TUDO QUE NAO SEJA NUMERO

    for(var i = 0; i <= mask.substrCount('#'); i++){

        if(typeof(value[i]) === 'undefined'){
            break;
        } 

        var k = mask.indexOf('#');  // CAPTURA O PROXIMO INDICE DE #
        mask = mask.split('');
        mask[k] = value[i];
        mask = mask.join('');
    }

    return mask;
}

In PHP I have it just like this:

function maskNumber($mask,$str){
    $str = onlyNumber($str);    // REMOVE TUDO QUE NAO SEJA NUMERO

    $count = mb_substr_count($mask, '#');
    for($i = 0; $i < $count; $i++){
        $mask[strpos($mask,"#")] = $str[$i];
    }

    return $mask;
}
    
asked by anonymous 25.09.2015 / 15:04

1 answer

2

I wrote something below that will help, but I think I'd better use some library for mask, in jquery , angular , Pure js .

Below is the built-in code in the plunker:

25.09.2015 / 15:49