Alexandru Dincă Alexandru Dincă - 1 month ago 8
CSS Question

jQuery: Extract the text from a div and put it in paragraphs

I have a div like this:

<div id="slidecaption"> Some text here. Some other text </div>


I want to extract the text from that div until I reach that "." and put it in a new paragraph and the text after "." in another paragraph.

Answer

You can use jQuery html(function) and iterate an array split by dot.

$('#slidecaption').html(function(_, existing) {
  return existing.trim().split('.').map(function(txt) {
    return txt.length ? $('<p>').text(txt + '.') : '';
  });
});
p {
  border: 1px solid #ccc;
  margin: 10px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slidecaption">Some text here. Some other text.</div>

Assumes that the only dots will be periods at end of sentences