The method split
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 turn it into a string before using the split
. Thus:
var num = 123456789; // numero
var variavel = num.toString(); // transforma em string
var caractere = variavel.split(''); // usa o split()
You can also use the charAt
, thus:
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 mode if the variable is a String
:
As suggested by @Isac and @lazyFox.
you can also use the indexing operator directly on a
string
, without the need to use the split
or chatAt
Thus:
var variavel = "123456789";
alert(variavel[0]); // retorna 1
You can show what you’ve tried, what the doubt?
– Ricardo Pontual
this is for some exercise? otherwise there is no reason to create a variable for each occurrence but an array
– Felipe Duarte