I am writing a program in Angular which displays short texts. In these texts I want to blur a certain substring, EACH time it occurs.
E.g. Tomorrow I will have to go to London. Tomorrow is the day it will happen. My only hope is tomorrow.
Here I would want to blur the text 'tomorrow', three times. Sometimes the substring occurs once, sometimes twice, ... or five times.
A tap or click on the words or on the paragraph UNBLURS them.
I did it with an indexOf function, put the substring into a span with a different class and an ngStyle attribute. But this does it only for the first occurrence of the substring.
const position = quoteL.indexOf(titleL);
if (position > -1) { // if the substr appears in the quote -> chop up the string and blur it
this.p1= quote?.substring(0, position);
this.p2= quote?.substring(position, position title.length);
this.p3= quote?.substring(position title.length, quote.length);
} else {
this.p1 = this.lyrics;
this.p2="";
this.p3=""
}
`
CodePudding user response:
I would start with this answer to wrap every word in span.
Regular expression for wrapping every word in span tag on word boundaries in javascript
Then I would change the span to have an ngClass or similar to see if the innerText or innerHTML is equal to the word being blurred.
If you had a stackblitz which a minimal reproducible example I could be more specific.....
CodePudding user response:
My realisation with regular expression. Example on pure JS.
.highlighted {
opacity: .3;
}
<p id="text">Tomorrow I will have to go to London. Tomorrow is the day it will happen. My only hope is tomorrow.</p>
<button onclick="highlightQueryStr('Tomorrow')">highlightQuery</button>
<script>
function highlightQueryStr(query) {
const textEl = document.querySelector("#text");
const reg = new RegExp(query,"gi");
textEl.innerHTML = textEl.innerHTML.replace(reg, `<span
>${query}</span>`);
}
</script>