Q:

jQuery: Insert " " before last word of every 

For typographic reasons, I would like to replace the normal space before every last word of every <p> with a &nbsp;.
Is it possible to do this with jQuery?

var lastword = str.split(" ").pop();

$("p").(" lastword").replaceWith("&nbsp;lastword");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam era.</p>
<p>At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</p>
<p>Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
<p>At vero eos et accusam et justo duo dolores et ea rebum.</p>

Would be verrrrry thankful for help! :)

A:

Use a regular expression and match \s\b(?=\S+$) (a space, followed by non-spaces and the end of a string) and replace with the &nbsp:

for (const p of $('p')) {
  p.innerHTML = p.innerHTML.replace(/\s\b(?=\S+$)/, '&nbsp');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam era.</p>
<p>At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</p>
<p>Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
<p>At vero eos et accusam et justo duo dolores et ea rebum.</p>

Or, since jQuery is only being used for selection, may as well drop it and use querySelectorAll:

for (const p of document.querySelectorAll('p')) {
  p.innerHTML = p.innerHTML.replace(/\s\b(?=\S+$)/, '&nbsp');
}
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam era.</p>
<p>At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</p>
<p>Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
<p>At vero eos et accusam et justo duo dolores et ea rebum.</p>

