开发者

Given an ID, find and replace the last sentence with a span wrapper

开发者 https://www.devze.com 2023-01-08 03:08 出处:网络
Given the following: <div id=\"bigchuck\"> <p>blah blah blah.</p> <p>yada yada yada.</p>

Given the following:

<div id="bigchuck">
 <p>blah blah blah.</p>
 <p>yada yada yada.</p>
 <p>Tada. Bing bong the witch is dead. Door bell.</p>
</div>

How can JavaScript/JQUERY find the last sentence "Door bell" and wrap it with a tag, to re开发者_高级运维sult in:

<div id="bigchuck">
 <p>blah blah blah.</p>
 <p>yada yada yada.</p>
 <p>Tada. Bing bong the witch is dead. <span>Door bell.</span></p>
</div>

Thank you


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.


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('');
});


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("."));
0

精彩评论

暂无评论...
验证码 换一张
取 消