Transform variable into array

Asked

Viewed 334 times

1

I have a variable that calls all people names.

var nome = "João Miguel Pedro";

How do I make it become the following array:

var nome1 = ["João","Miguel","Pedro"];

1 answer

5


In the first case, an option is to use the split() to separate by space. See:

var nome = "João Miguel Pedro"

var nome1 = nome.split(" ");

console.log(nome1);

Or you can make one regex to make a split() by capital letters, as you questioned in the comments. See:

var nome = "JoãoMiguelPedro"

var nome1 = nome.split(/(?=[A-Z])/);

console.log(nome1);

  • Okay, but if there’s no room?

  • 1

    @Felipemichaeldafonseca for example if you have a comma, you can do it the same way. var nome = "João,Miguel,Pedro" that would be so: nome.split(",")... Otherwise, you’d have to go into more detail about your problem for us to try to solve.

  • The problem is that the variable brings: Joãomiguelpedro, no spaces with nothing. I just need to know how I do to catch these values. If I use the split it won’t catch

  • @Felipemichaeldafonseca in his example only had by space. I edited the question by making a split with capital letters.

  • 1

    Thanks now it worked out

  • @Felipemichaeldafonseca if you want to validate the answer, feel free. = D

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.