You are using String.prototype.split () .
This function should be used as follows:
According to the mozilla documentation the function has the following syntax
cadena.split([separador][,limite])
Where
separator
Specifies the character to use for chain separation. The
Separator is treated as a string or as a regular expression. Yes
the separator is omitted, the returned array will contain a single element
with the full chain.
limit
Optional. Integer that specifies a limit on the number of
divisions to be made. The split () method is still divided in all
matches the separator, but divides the matrix returned in the
amount of elements imposed by the limit.
Taking this to your particular case, it is understood that having an error in the next line
var separa = nombre.split(".");
where the right thing would be
var separa = nombre.split(" ",2);
As you can see, use the function split()
with 2 arguments, where, as the first parameter, a space will pass, since the name will be separated by a space, and as a second parameter it will pass an integer 2
, since I hope it's only two words that I receive.
So it would produce the following
nombre: Marcos Perez
separa[0]: Marcos
separa[1]: Perez
nombre: Gonzalo Martinez Gomez
separa[0]: Gonzalo
separa[1]: Martinez
separa[2]: no existe debido al segundo parámetro de split()
Then, having already managed to separate the name and surname, it would only suffice to concatenate separa[0]
with the first character of separa[1]
var resultado = separa[0] + " " + separa[1].charAt(0)+".";