Last active
November 8, 2019 14:07
-
-
Save GoSubRoutine/de13a236ab6cc666320d39a1b04a2315 to your computer and use it in GitHub Desktop.
Colorize Each Word
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
height: 85 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset=utf-8> | |
<script async src=http://cdn.JsDelivr.net/npm/p5></script> | |
<script defer src=sketch.js></script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Colorize Each Word (v3.0) | |
* GoToLoop (2017-Aug-13) | |
* | |
* https://Forum.Processing.org/two/discussion/23783/ | |
* how-can-i-style-specific-words-within-a-string#Item_14 | |
* | |
* http://Bl.ocks.org/GoSubRoutine/de13a236ab6cc666320d39a1b04a2315 | |
* https://OpenProcessing.org/sketch/443843 | |
*/ | |
"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() { | |
noCanvas(); | |
for (const msg of SENTENCES) | |
//createP(Colorize.colorizeWords(msg, COLOR_WORDS)); | |
createP(Colorize.colorizeWords(msg, COLOR_WORDS, true)); | |
} | |
class Colorize { | |
static get RE() { | |
delete this.RE; | |
//return this.RE = /[-'\w\xC0-\u02AF]+/g; | |
return this.RE = /\w{3,}/g; | |
} | |
static get SPAN_OPEN() { | |
delete this.SPAN_OPEN; | |
return this.SPAN_OPEN = '<span style=background-color:'; | |
} | |
static get SPAN_CLOSE() { | |
delete this.SPAN_CLOSE; | |
return this.SPAN_CLOSE = '</span>'; | |
} | |
static get GT() { | |
delete this.GT; | |
return this.GT = '>'; | |
} | |
static colorizeWords(txt, words, isBG) { | |
if (words) this.colorWords = words; | |
return txt.replace(this.RE, isBG && this.MatchBG || this.MatchFG); | |
} | |
static MatchFG(matched) { | |
const colour = Colorize.colorWords[matched.toLowerCase()]; | |
return colour && matched.fontcolor(colour) || matched; | |
} | |
static MatchBG(matched) { | |
const C = Colorize, colour = C.colorWords[matched.toLowerCase()]; | |
return !colour && matched || | |
C.SPAN_OPEN + colour + C.GT + matched + C.SPAN_CLOSE; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment