How do I break “text” apart and put it into an array?
let input, button, greeting;
function setup() {
// create canvas
createCanvas(710, 400);
input = createInput();
input.position(20, 65);
button = createButton('submit');
button.position(input.x + input.width, 65);
button.mousePressed(greet);
greeting = createElement('h2', 'what do you want Rick to say?');
greeting.position(20, 5);
textAlign(CENTER);
textSize(50);
}
function greet() {
const text = input.value();
}
in a sense, the string is an array
use charAt to get the elements:
see last line
let input, button, greeting;
function setup() {
// create canvas
createCanvas(710, 400);
input = createInput();
input.position(20, 65);
button = createButton('submit');
button.position(input.x + input.width, 65);
button.mousePressed(greet);
greeting = createElement('h2', 'what do you want Rick to say?');
greeting.position(20, 5);
textAlign(CENTER);
textSize(50);
}
function greet() {
let text = input.value();
console.log(text.charAt(3)); // !!!!
}
Characters within a JS string can be individually read using the operator []
just like an array:
However if you prefer to convert it into an actual array you can invoke its String ::split() function passing an empty string as its parameter:
const text = input.value();
→ const chars = input.value().split('');
The split() method of String values takes a pattern and divides this string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
For “word” splitting instead of an array of characters take a look at both split() & splitTokens() :
reference | p5.js
reference | p5.js