Andrey Shandrov Andrey Shandrov - 5 months ago 17
jQuery Question

how to wrap text after symbol

I have this line of text

<p>"May you live all the days of your life." — Jonathan Swift</p>


how to wrap this part "— Jonathan Swift" in span, so the result will be like:

<p>"May you live all the days of your life." <span>— Jonathan Swift</span></p>

Answer

You can use String#replace with html() method.

$('p').html(function(i, v) {
  return v.replace(/\—.*$/, '<span>$&</span>')
});
p span {
  color: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>"May you live all the days of your life." — Jonathan Swift</p>

Or using String#substr method.

$('p').html(function(i, v) {
  var ind = v.indexOf('—');
  return v.substr(0, ind) + '<span>' + v.substr(ind) + '</span>';
});
p span {
  color: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>"May you live all the days of your life." — Jonathan Swift</p>