xxxxxxxxxx
/**
* Colorize Each Word (v1.2.1)
* GoToLoop (2017-Aug-13)
*
* https://Forum.Processing.org/two/discussion/23783/
* how-can-i-style-specific-words-within-a-string#Item_12
*
* https://OpenProcessing.org/sketch/443843
* http://Bl.ocks.org/GoSubRoutine/de13a236ab6cc666320d39a1b04a2315
*/
"use strict";
const SENTENCES = [
'Hello tree ciao. House adios!',
`In the morning I've been in the park,
I had chicken for lunch and then
I went biking with my friends.`
],
COLOR_WORDS = {
house: 'Blue',
tree: 'LawnGreen',
park: 'MediumOrchid',
chicken: 'Peru',
friends: 'OrangeRed'
};
function setup() {
background('white').noCanvas();
for (const msg of SENTENCES)
createP(colorizeWords(msg, COLOR_WORDS));
//createP(colorizeBGWords(msg, COLOR_WORDS));
}
function colorizeWords(txt, words) {
const flags = 'gi', matched = '$&';
for (const w in words) {
const re = RegExp(w, flags), col = words[w];
txt = txt.replace(re, matched.fontcolor(col));
}
return txt;
}
function colorizeBGWords(txt, words) {
const flags = 'gi', matched = '$&',
span = '<span style=background-color:',
close = '>' + matched + '</span>';
for (const w in words) {
const re = RegExp(w, flags), col = words[w];
txt = txt.replace(re, span + col + close);
}
return txt;
}