Regular Expressions 101

Community Patterns

Community Library Entry

0

Regular Expression
PCRE (PHP <7.3)

/
^([0-9]{3})\.?([0-9]{3})\.?([0-9]{3})\-?([0-9]{2})$
/
gm

Description

const cpfMask = (cpf) => { 
  
  if (/[a-zA-Z]|\W/.test(cpf)) {
    return cpf.replace(/[a-zA-Z]|\W/, "");
  }

  return cpf.replace(/^([0-9]{3})\.?([0-9]{3})\.?([0-9]{3})\-?([0-9]{2})$/, "$1.$2.$3-$4"); 

  
}
Submitted by coderpy - 6 years ago