How to store words from a text in an array

Asked

Viewed 600 times

1

I need to create a function that takes a text and stores each word in an array. In c# I know there is the Tochararray() function and with that I just need to do a "go" to and check when there is a blank space, but how do I do it in js?

  • To create an array of words just do texto.split(" ")

2 answers

1

use the . split function and assign the phrase in an array

function guarda_palavra(){
       
      text = document.getElementById('texto').value; 
      var arr = text.split(" ");
      
      alert('array com a frase escrita: '+arr);

}
<input type='text' id='texto' placeholder='digite a frase'>
<button onclick="guarda_palavra('minha frase')">click </button>

1

You can use the function split

If you need to separate words, pass the desired separate as a parameter:

var text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit';

var arrayDePalavras = text.split(' ');
// note que estou usando um espaço em branco. Poderia ser qualquer outro caracter, como um hífen, por exemplo. Ou até mesmo uma palavra.

console.log(arrayDePalavras );

And if you need an effect similar to the Tochararray of C#, pass an empty string as parameter:

var text = 'Lorem ipsum dolor sit amet';
var arrayDeCaracteres = text.split('');
console.log(arrayDeCaracteres);

Browser other questions tagged

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