cup_of
cup_of

Reputation: 6687

Wrap the last word of a paragraph in span tags using jQuery

Hello say I have the following html:

<p>Phasellus sit amet auctor velit, ac egestas augue.</p>

I would like to wrap the last word in span tags so the result will be:

<p>Phasellus sit amet auctor velit, ac egestas <span>augue.</span></p>

The logic would be something like:

var paragraph = $("p");
var lastWord = /* target the last word */
lastWord.wrap("<span></span>");

Thanks!

Upvotes: 0

Views: 1341

Answers (3)

Nick Arocho
Nick Arocho

Reputation: 3

// target the string
const string = document.querySelector('.string');

// split the words of the string into an array
const wordsOfStringArray = string.innerHTML.split(' ');

// isolate the last word and remove from string
const lastWordOfString = wordsOfStringArray.pop();

// wrap the last word in a span tag to style independently
const newStringHTML = `
    ${wordsOfStringArray.join(' ')} <span class="last">${lastWordOfString}</span>
`;

// finally, replace the HTML with the new markup
string.innerHTML = newStringHTML;
.last {
    /* knock urself out */
    color: tomato;
    font-size: 2em;
}
<p class="string">Phasellus sit amet auctor velit, ac egestas augue.</p>

Upvotes: 0

Braijon G.
Braijon G.

Reputation: 91

I broke this problem down into multiple steps for an easier understanding of what must be done - Hope it helps:

const paragraph = $('p');

let paragraphWords = $(paragraph).text().split(' ');

let lastWordIndex = paragraphWords.length - 1;
let lastWord = paragraphWords[lastWordIndex];
let lastWordModified = `<span>${lastWord}</span>`;

paragraphWords[lastWordIndex] = lastWordModified;

let newParagraphWords = paragraphWords.join(' ');

$(paragraph).html(newParagraphWords);

Upvotes: 1

devil
devil

Reputation: 106

I Hope this code is helpful for you :)

jQuery(document).ready(function($){  
		
	$('p').html(function(){	
		// separate the text by spaces
		var text= $(this).text().split(' ');
		// drop the last word and store it in a variable
		var last = text.pop();
		// join the text back and if it has more than 1 word add the span tag
		// to the last word
		return text.join(" ") + (text.length > 0 ? ' <span class="last">'+last+'</span>' : last);   
	});

});
span{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Phasellus sit amet auctor velit, ac egestas augue.</p>

Upvotes: 2

Related Questions