variable catch certain numbers

0

Good afternoon guys.

I need a variable to always get a certain number from an order, for example:

user types 123456789

  

Variable to : Always pick the first number in the string, that is, 1

     

Variable b : Always take the second number in the series, that is, 2

and so on.

    
asked by anonymous 19.03.2018 / 16:58

2 answers

3

The split method separates characters from a word when the delimiter is not informed. So:

var variavel = "123456789";
var caractere = variavel.split(''); // aqui ele separa a string

var variavel_A = caractere[0]; // primeiro caractere
var variavel_B = caractere[1]; // segundo caractere
var variavel_C = caractere[2]; // terceiro caractere
var variavel_D = caractere[3]; // quarto caractere

alert(variavel_A ); // retornará "1" 
alert(variavel_B); // retornará "2"
alert(variavel_C); // retornará "3"
alert(variavel_D); // retornará "4"

If the variable is a number, you will need to convert it to a string before using split . So:

var num = 123456789; // numero
var variavel = num.toString(); // transforma em string
var caractere = variavel.split(''); // usa o split()

You can also use charAt , like this:

var variavel = "123456789";

var variavel_A = variavel.charAt(0); // primeiro caractere
var variavel_B = variavel.charAt(1); // segundo caractere
var variavel_C = variavel.charAt(2); // terceiro caractere
var variavel_D = variavel.charAt(3); // quarto caractere

There is a more indicated way if the variable is a String :

As suggested by @Isac and @lazyFox.

  

You can also use the index operator directly over a    string , without the need to use split or chatAt

In this way:

var variavel = "123456789";
alert(variavel[0]); // retorna 1
    
19.03.2018 / 17:18
1

You can dynamically create the number of variables according to the number of digits in the string

	var variavel = "123456789";
	//quantidade de dígitos na variável acima
	var n = variavel.length;
	var caractere = variavel.split('');
  
	 //criando as variáveis dinamicamente
	 for (var i = 0; i < n; i++)
	 {
	 var char_A = i+1;
	 var letra = (String.fromCharCode(char_A+64))
	 window["variavel" + letra] = (caractere[i]);
	 }
		
	//verificando algumas variaveis 
	console.log( "O valor da variavelA é " + variavelA);

    console.log( "O valor da variavelB é " + variavelB);
	
	console.log( "O valor da variavelE é " + variavelE);
  
  
   
	 //Para recuperar os valores de todas as variáveis
	 for (var i = 0; i <n; i++)
	 {
	 var char_A = i+1;
	 var letra = (String.fromCharCode(char_A+64))
	 console.log(window["variavel" + letra]);
	 }
   

The split () method splits a String object in an array of strings by separating the string into substrings.

The method String.fromCharCode () returns a string created when using a specific sequence of Unicode values.

    
19.03.2018 / 20:23