Select punctuation marks immediately adjacent to the links, wrap them in between

I would like to use jQuery for:

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

This implies:

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

to become next:

<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, &ldquoand &rdquo;are quotation marks.)

The content in is divnot fixed. There may also be cases where next to the link (for example, higher, &rdquo;.more than one punctuation mark) becomes <span>&rdquo;.</span>)

It would be very helpful to help !!


Sort of similar (but not quite) to this question regarding the choice of text nodes? Using jQuery, how to change text outside tags?

+3
2

:

: 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: , - , .

+2

: , div div (, mydiv)?

<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>

- patrick :

$('.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 );
});

- http://jsfiddle.net/ZEC3X/ - , / ?

0

Source: https://habr.com/ru/post/1750882/


All Articles