JSFiddle - React, Tailwind, and code Playground
by tara5
HTML
<!DOCTYPE html>
<html>
<head>
<title>RegExp Replace</title>
<style>
.tip {
color: blue;
text-decoration: underline;
}
</style>
</head>
<body>
<div id="text-section-article">
The activity patient is correspond to Weekly activity minutes of sleep
</div>
</body>
</html>
JavaScript
let keywords = {
"activity" : {
phrases: ["activity", 'Weekly activity minutes']
},
'sleep': {
phrases: ["sleep"]
}
}
let patient = {
weight: 60,
height: 70,
'currents' : {
"activity" : 100,
"sleep" : 60
},
}
let text = document.getElementById('text-section-article').textContent.trim();
let splitText = text.split(' ');
let textByPhrases = [].concat(splitText);
let phraseIndexToPatientCurrentsKey = {};
Object.entries(keywords).forEach(([key, values]) => {
const phrases = [].concat(values.phrases).sort((a, b) => {
return b.length - a.length;
});
phrases.forEach((phrase) => {
const splitPhrase = phrase.split(' ');
if (patient.currents.hasOwnProperty(key)) {
let phraseByWord = [];
let memo = [];
for (let i = 0; i < textByPhrases.length; i++) {
let k = i;
for (let j = 0; j < splitPhrase.length; j++) {
let word = textByPhrases[k];
let phraseWord = splitPhrase[j];
if (word === phraseWord) {
phraseByWord.push(word);
if (phraseByWord.length < splitPhrase.length) {
k = k + 1;
}
} else {
phrase = [];
break;
}
}
if (phraseByWord.length > 0) {
i = k;
phraseIndexToPatientCurrentsKey[memo.length] = key;
memo.push(phraseByWord.join(' '));
phraseByWord = [];
} else {
memo.push(textByPhrases[i]);
}
}
textByPhrases = memo;
}
});
});
text = textByPhrases.map((phrase, index) => {
const key = phraseIndexToPatientCurrentsKey[index];
if (key) {
let title = `Your current ${phrase} is ${patient.currents[key]}`;
return '<span data-toggle="tooltip" title="' + title + '" class="tip ' + phrase + '">' + phrase + '</span>'
}
return phrase;
}).join(' ');
document.getElementById('text-section-article').innerHTML = text;