I want to wrap an apostrophe that appears in h1 tags and character immediately before it. e.g. <h1>Can't</h1>
would be like this <h1>Ca<span>n'</span>t</h1>
I can do the apostrophe part using the following
$("h1:contains('')").html(function(_, html) {
return html.replace(/(')/g, '<span>$1</span>');
});
span { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Can't</h1>
How would I go about selecting the character before the apostrophe?
2
Answers
Add a class to the regex:
[a-z]
The OP mainly has two
RegExp
pattern options to choose from …/(?<=p{L})'(?=p{L})/gu
utilizes a lookaround (both positive lookbehind and lookahead), where, for thereplace
ment, the OP does neither need a reference to the letter before nor to the letter after the single quote, not even to the single quote itself; thus the OP could just go with a string-based replacement-pattern like<span>'</span>
. For the match itself included into the string the latter would change to …<span>$&</span>
.Note: The above also is the correct approach for targeting any apostrophe / single quote which is supposed to be both, lead and followed by a letter, whereas the OP’s code would just wrap any occurring apostrophe.
/(p{L})'(p{L})/gu
uses two unnamed capturing groups, where one then needs to go for a replacement-function which gets the match and the group values passed in as arguments … with the function then looking like this …(match, before, after) => `<span>${ before }'</span>${ after }`
… in order to fulfill the OP’s requirement of the additionally highlighted leading letter.Note: The second approach of cause also would serve the case of the solely highlighted apostrophe …
(match, before, after) => `${ before }<span>'</span>${ after }`
.