Wrap First & Last Word in jQuery

by Faisal Khan Janjua

HTML

<div class="messageOnly1st">Lorem Ipsum to the new place with other Colors</div>
<br>
<div class="messageOnlyLast">Lorem Ipsum to the new place with other Colors</div>
<br>
<div class="messageBoth">Lorem Ipsum to the new place with other Colors</div>

CSS

.em { color:#00c0ff; }
.last{ color:#e400ff; }

JavaScript

$('.messageOnly1st').each(function() {
  var html1 = $(this).html();
  var fword1 = html1.substr(0, html1.indexOf(" "));
  var rest1 = html1.substr(html1.indexOf(" "));
  $(this).html(rest1).prepend("<span class='em'>" + fword1 + "</span>");
});
$('.messageOnlyLast').each(function() {
  var html2 = $(this).html();
  var lword2 = html2.substr(html2.lastIndexOf(" "));
  var rest2 = html2.substr(0, html2.lastIndexOf(" "));
  $(this).html(rest2).append("<span class='last'>" + lword2 + "</span>");
});
$('.messageBoth').each(function() {
  var html3 = $(this).html();
  var fword3 = html3.substr(0, html3.indexOf(" "));
  var lword3 = html3.substr(html3.lastIndexOf(" "));
  var rest3 = html3.substr(html3.indexOf(" "));
  var nrest3 = rest3.substr(0, rest3.lastIndexOf(" "));
  $(this).html(nrest3).prepend("<span class='em'>" + fword3 + "</span>");
  $(this).append("<span class='last'>" + lword3 + "</span>");
});