Targeting string to wrap with HTML element to italicize Objective
I set up my page to dynamically wrap &lt;i&gt; tags around a targeted keyword (string) on a title.
Background
When I worked on the static parts of the website, I could manually wrap that word. But Some parts of the page will be generated by the server, so if the word appears in the title, I need it wrapped so that it shows up as italicized.
For the sake of an example, let's say that if the keyword is &quot;cool&quot; then it needs to be converted to &lt;i&gt;cool&lt;/i&gt; if it appears in a title, which in this case is class &quot;exec-company&quot;
&lt;div class=&quot;exec-company&quot;&gt;&lt;?php the_field('company') ?&gt;&lt;/div&gt;

Lets say the output was this HTML
&lt;div class=&quot;exec-company&quot;&gt;Cool company&lt;/div&gt;

I followed along to this tutorial. Which advised on using jQuery and showed this sample
var oldString = 'john',
newString = '&lt;span&gt;John&lt;/span&gt;',
newText = $('p').text().replace(RegExp(oldString,&quot;gi&quot;),newString);

$('p').html(newText);

I modified to this so that it is always uppercase, and always italicized
var oldString = 'cool',
newString = '&lt;i&gt;COOL&lt;/i&gt;',
newText = $('.exec-company').text().replace(RegExp(oldString,&quot;gi&quot;),newString);

$('.exec-company').html(newText);

On codepen, I made a demo which produced this.

but wondering if this was the best way to approach this problem. Especially since the solution won't really scale well since the word is used site wide.
First of all, I would highly recommend NOT doing this in JS for the following reasons:


You'd have JS scan through words, which may be slow.
FOUC, where the word is not italic until the JS runs.
jquery.text() captures newlines and whitespace. If the word is split with unexpected newlines in between, the script breaks.
jquery.html replaces HTML using innerHTML. This means:


Existing event handlers, especially those created by frameworks, are not cleaned up properly.
Existing event handlers will not be re-attached to your new HTML.



In addition to that, I suggest not hardcoding the replacement string. Use capture groups to have RegExp capture the match. Then convert the matched string to upper case and wrap it with the element afterwards. That way, you don't have hard-coded replacements, only the searches.

What I highly suggest is to do this on the PHP side instead. You can take the same logic, except just to it there. I believe preg_replace is what you need for this. If you cannot access the server-side code, then request access.

JS might be the quick and easy way to do this, but stuff like this over time leads to fragmented, highly unmaintainable, and hard-to-find code. A normal developer would think "Hey, it's probably italicized in the source." until they find out days later (yes, days) it was never in PHP. Thenthey'll have to hunt it down in JS, except they won't know where to start.