Enter variable in regular expressions

1

I'm trying to pass a variable to a regular expression (so I can modify it to my liking) in this case I want to enter a number so that I can control the number of digits allowed.

I can not make it work, or pass it as a separate string ... nothing. Any ideas?

Thank you.

function ValidarFormato(longitud_numero,evento_disparado){
	var ExpReg = new RegExp("^\d{" + longitud_numero + "}$");
	
  //Expresion regular con la que funciona
  //var patt = new RegExp(/^\d{4}$/);
  
  var valor = evento_disparado.value;
  
	console.log("Patron:"+ExpReg+" |Valor introducido:"+valor);
	if( !(ExpReg.test(valor)) ) {
		console.log("false");
		return false;
	}else{
		console.log("true");
		return true;
	}
}

function asignarEventos()
{
   if (document['readyState'] == 'complete')
   {
   	 //Input Entradad
	   input_entrada = document.getElementById("input_entrada");
	  //Boton Buscar 
	  btn_entrada = document.getElementById("btn_entrada");
	   btn_entrada.addEventListener('click',function(){
		  ValidarFormato(4,input_entrada);
		  });
	}
}
document.addEventListener('readystatechange', asignarEventos, false);
	<input  id="input_entrada"></input>
	<button  id="btn_entrada">Entrada</button>
    
asked by Roarca 27.09.2018 в 23:22
source

1 answer

1

Change this line:

var ExpReg = new RegExp("^\d{" + longitud_numero + "}$");

By:

var ExpReg = new RegExp("^\d{" + longitud_numero + "}$");
  

That is, add another backslash in front of the d

According to the page: link

When the constructor function is used, the normal rule escape string (preceded by the special character \ when it includes a string) is necessary. For example, the following is equivalent:

var re = new RegExp("\w+");
var re = /\w+/;
    
answered by 27.09.2018 / 23:29
source