开发者

Select punctuation marks directly adjacent to links, wrap them in spans

开发者 https://www.devze.com 2023-01-04 14:44 出处:网络
Would like to use jQuery to: select any punctuation marks (meaning . , ; : \' \" “ ” ‘ ’ etc.) that occur directly before and after any links and then

Would like to use jQuery to:

  1. select any punctuation marks (meaning . , ; : ' " “ ” ‘ ’ etc.) that occur directly before and after any links and then
  2. wrap the punctuation marks in spans.

Hence this:

<div id="mydiv">
  Lorem ipsum
  <a href="#">dolor sit amet</a>,
  consectetur
  &ldquo;<a href="#">adipisicing elit</a>&rdquo;.
</div>

to become this:

<div id="mydiv">
  Lorem ipsum
  <a href="#">dolor sit amet</a><span>,</span>
  consectetur
  <span>&ldquo;</span><a href="#">adipisicing elit</a><span>&rdquo;.</span>
</div>

(BTW, &ldquo and &rdquo; 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, &rdquo;. to become <span>&rdquo;.</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
  &ldquo;<a href="#">adipisicing elit</a>&rdquo;.
</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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号