Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace characters in a series of headlines

I’m working with feed that I have no control over. I need to replace the first half pipe character in each of a number of headlines with a <div> e.g.

<h3>New Clause 12 - Monitoring tool | Order | Committees</h3>

Changes to

<h3>New Clause 12 - Monitoring tool</h3><div> Order | Committees </div>

This script works, but it’s replacing all instances of | and replacing the entire contents of every h3 on the page with the content of the first headline. How can I limit the scope of the script to affect only the first | and leave the headlines text content unaltered?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

jQuery('h3').html(jQuery('h3').html().replace('|', "</h3><div>"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>New Clause 12 - Monitoring tool | Order | Committees</h3>

>Solution :

Your approach unfortunately doesn’t work as you can’t split elements as you’re attempting. You can only amend/insert entire elements.

To do what you require, select the h3 element, get the text you require from it and place that in to a new div which you insert after the h3, like this:

$('h3').each((i, h3) => {
  let $h3 = $(h3);
  let text = $h3.text().split('|');
  $h3.text(text[0].trim());
  $('<div />').text(text.slice(1).join('|')).insertAfter($h3);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>New Clause 12 - Monitoring tool | Order | Committees</h3>

<h3>Foo | Bar | Foobar</h3>

<h3>Lorem | Ipsum | Dolor</h3>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading