Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript / jquery - Grab first and last word from string then wrap with class

Tags:

So I have a blockquote:

<blockquote>
 <p>We seek to innovate: not for the sake of doing something different, but doing something
 better.</p>
</blockquote>

What I need to do is grab the first and last word from the string. Then I need to wrap <span class="firstWord"></span> around the first word and <span class="lastWord"></span> around the last word in the sentence.

FYI - The text will constantly change so the first and last word WILL NOT always be the same word.

Is there a way for me to do this?

like image 552
agon024 Avatar asked Oct 16 '16 22:10

agon024


2 Answers

Using jQuery first split the text into array, modify first and last element in array and then join array

$('blockquote p').html(function(_, existing) {
  var words = existing.trim().split(' ');
  words[0] = '<span class="firstword">' + words[0] + '</span>';
  words[words.length - 1] = '<span class="lastword">' + words[words.length - 1] + '</span>';
  return words.join(' ');
});
.firstword,
.lastword {
  color: red;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<blockquote>
  <p>We seek to innovate: not for the sake of doing something different, but doing something better.</p>
</blockquote>
like image 94
charlietfl Avatar answered Oct 03 '22 19:10

charlietfl


With jQuery:

I jsfiddle:

 var blockquote = $('p').text(), //get the text inside <p>

    bkFirst = blockquote.split(" ", 1), //get first word
    bkLast = blockquote.substring(blockquote.lastIndexOf(" ")+1), //get last word
    bkRemL = blockquote.substring(0, blockquote.lastIndexOf(" ")), //remove last word from original string (blockquote)
    bkMid = bkRemL.substr(bkRemL.indexOf(" ") + 1), //remove first word from bkRemL, to get all words but first and last.
    first = '<span class="firstWord">'+bkFirst+'</span>', //append first word on the span
    last = '<span class="lastWord">'+bkLast+'</span>'; //append last word on the span

$('p').html(first+' '+bkMid+' '+last); //join all of them.
.firstWord {
color: red;}

.lastWord {
color: blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>A simple sentence with few words</p>
like image 26
sandrina-p Avatar answered Oct 03 '22 17:10

sandrina-p