I need to create a function that takes a text and stores each word in an array. In C # I know the ToCharArray () function exists and with this I just need to do a "for" to and check when there is a blank space, but how do I do this in js?
I need to create a function that takes a text and stores each word in an array. In C # I know the ToCharArray () function exists and with this I just need to do a "for" to and check when there is a blank space, but how do I do this in js?
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>
You can use the split
If you need to separate words, pass as desired the separated 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 C #'s ToCharArray, pass an empty string as a parameter:
var text = 'Lorem ipsum dolor sit amet';
var arrayDeCaracteres = text.split('');
console.log(arrayDeCaracteres);