Select punctuation marks directly adjacent to links, wrap them in spans
Would like to use jQuery to:
- select any punctuation marks (meaning
.
,
;
:
'
"
“
”
‘
’
etc.) that occur directly before and after any links and then - wrap the punctuation marks in
span
s.
Hence this:
<div id="mydiv">
Lorem ipsum
<a href="#">dolor sit amet</a>,
consectetur
“<a href="#">adipisicing elit</a>”.
</div>
to become this:
<div id="mydiv">
Lorem ipsum
<a href="#">dolor sit amet</a><span>,</span>
consectetur
<span>“</span><a href="#">adipisicing elit</a><span>”.</span>
</div>
(BTW, &ldquo
and ”
are quotation marks.)
The content in the div
is开发者_高级运维 not fixed. There may also be instances where there's more than one punctuation mark adjacent to a link (as in the above, ”.
to become <span>”.</span>
)
Would really appreciate any help!!
Sorta similar (but not quite) to this question with regards to selecting text nodes? Using jQuery, how to modify text outside of tags?
This seems to work:
Try it out: http://jsfiddle.net/GutKg/1/
var $div = $('#mydiv');
var html = $div.html();
html = html.replace(/([^\s\w]+)<a/g, '<span>$1</span><a')
.replace(/<\/a>([^\s\w]+)/g, '</a><span>$1</span>');
$div.html( html );
EDIT: Updated to exclude alphanumeric characters adjacent to the tags.
Extending my question somewhat: what if instead of a lone div
with an id, there were many instances of the div
(say with the class mydiv
) throughout the page?
<div class="mydiv">
Lorem ipsum
<a href="#">dolor sit amet</a>,
consectetur
“<a href="#">adipisicing elit</a>”.
</div>
<div class="mydiv">
Ei vel <a href="#">velit mollis vivendo</a>.
</div>
Cobbled something together off patrick's solution:
$('.mydiv').each(function () {
html = $(this).html().replace(/([^\s\w]+)<a/g, '<span>$1</span><a')
.replace(/<\/a>([^\s\w]+)/g, '</a><span>$1</span>');
$(this).html( html );
});
It works -- http://jsfiddle.net/ZEC3X/ -- but I dunno, is it the most efficient/logical way to go about doing it?
精彩评论