Mask - Javascript Mascara

Asked

Viewed 598 times

1

I was transcribing some functions 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;
}
  • How does this function work ? Replaces # by numbers, that’s it ?

  • Yes, basically '72081338831'. Mask('###.##.###-##') = 720.813.388-31

  • 3

    See if those answers helping.

  • @rray was this question I’ve been looking for for a while.

  • That question not the opposite of what you want? now that I noticed LOL

  • Yes, but a while ago I was wanting to mount the PHP and did not find, so I researched more and found this, but now I want to transcribe to JS.

Show 1 more comment

1 answer

2


I wrote something below that will help you, but I think I better use some library for Mask, in jquery, angular, js pure.

Below follows the built-in code and plunker:
Mask code no plunker

String.prototype.mask = function(mask){
    var result = '';
    var value = this.replace(/\D/g, '');   // REMOVE TUDO QUE NAO SEJA NUMERO

    for (i = 0, j = 0; i < mask.length; i++) { 
      if (mask[i] == '#') {
        result += value[j] ? value[j] : '';
        j++;
      } else {
        result += mask[i];
      }
    }
    return result;
}

document.getElementById('xpto').innerHTML = '72081338831'.mask('###.###.###-##');
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <div id="xpto">initial value</div>    
  </body>

</html>

  • In fact I think transcribing the string is better than exploding and joining, but I will wait a little longer. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.