wrap the last word of a paragraph in span tags using jquery

Solutions on MaxInterview for wrap the last word of a paragraph in span tags using jquery by the best coders in the world

showing results for - "wrap the last word of a paragraph in span tags using jquery"
Federica
17 Mar 2017
1<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
2<p>Phasellus sit amet auctor velit, ac egestas augue.</p>
3<script>
4jQuery(document).ready(function($){  
5		
6	$('p').html(function(){	
7		// separate the text by spaces
8		var text= $(this).text().split(' ');
9		// drop the last word and store it in a variable
10		var last = text.pop();
11		// join the text back and if it has more than 1 word add the span tag
12		// to the last word
13		return text.join(" ") + (text.length > 0 ? ' <span class="last">'+last+'</span>' : last);   
14	});
15
16});
17</script>
18<style>
19span{
20color:red;
21}
22</style>
23
24