Skip to content Skip to sidebar Skip to footer

Given An Id, Find And Replace The Last Sentence With A Span Wrapper

Given the following:

blah blah blah.

yada yada yada.

Tada. Bing bong the witch is dead. Door bell.

Solution 1:

This solution is based on patrick's solution (he deserves the credit for coming up with the function(i,html) approach), but it just wraps the last sentence and not the space before it:

$('#bigchuck p:last').html( function(i,html) {
  var arr = html.split(". ");
  arr[arr.length-1]="<span>"+arr[arr.length-1]+"</span>";
  return arr.join(". ");
});

Here's the code in action.

Solution 2:

Try this:http://jsfiddle.net/NpjUt/

$('#bigchuck p:last').html( function(i,html) {
    var arr = html.split(/(\.)/);
    arr.splice(arr.length - 3, 0, '<span>');
    arr.push('</span>')
    return arr.join('');
});

Solution 3:

try this:

var plast = $("#bigchuck").find("p:last").text();

var part = plast.split("."), pos = part.length - 2;
if (part.length < 2)
  pos = 0;

part[pos] = "<span>" + part[pos] + ".</span>";
part.pop(); // <-edit for comment

$("#bigchuck").find("p:last").html(part.join("."));

Post a Comment for "Given An Id, Find And Replace The Last Sentence With A Span Wrapper"