How to apply changes to text on every occurance

How to apply changes to text on every occurance
0

#1

TLDR; Can I use jQuerty or CSS to make it so every time a certain word/phrase occurs in my < p > elements it is emphasized?

I’m trying to do the tribute page, and I’m writing about an author. I’m trying to make it so every time I mention one of his works the title is italicized without using < em > every time. Is there a way I can use jQuery or CSS to set it so every occurrence of the title gets italicized? I was thinking use:

$(“p”).html("< em >Title< /em >");

But this just gets rid of all the text inside the < p > element. For example if I had

“< p > Title is a book by author < /p >”

And used this jQuery function all that would be displayed is “Title” in italics, the additional words would be missing.


#2

You could play with regular expressions if you like.


#3

I’m still a beginner, can you please give me more information? Thanks.


#4

Regular expressions are a language for matching patterns in strings. They are incredibly powerful, but also devilishly complicated sometimes.

For example, we can replace Jones with <em>Jones</em> fairly simply.

$('p').html($('p').html().replace(/Jones/g, `<em>Jones</em>`));

But what if “Jones” is not always capitalized the same way? We want JONES to turn into JONES.
We can do that.

$('p').html($('p').html().replace(/(jones)/gi, `<em>$1</em>`));

But what if our author was born in Jonestown? We don’t want to turn that into Jonestown.
So we look for “Jones” surrounded by spaces.
But what if it is at the beginning of a paragraph? Now we have to match a space or a start of string.
And what if it is followed by punctuation instead of a space? We don’t want to make the punctuation italicized.
So we need a pattern that is along the lines of “The start of a string or a space character followed by (case insensitive) “Jones” followed by a space or a nonword character or the end of the string.” and a replacement that does not change or remove the characters before or after “Jones” but wraps “Jones” in the strings "<em>" and "</em>" without changing the capitalization.

//this example is left as an exercise for the reader

#5

(Note that the above code snippets are not necessarily the right way to do what you want. I just threw out a quick-and-dirty example.)


#6

Okay, this is helpful! Thanks!