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