开发者

With jQuery, how do I keep only the first sentence of some HTML, and keep the formatting?

Let's say I have some HTML like so:

<div id="text">This <i>is</i> a <b>test</b>. Do <i>not</i> be <b>alarmed</b>.</div>

I'd like to use jQuery to strip out the first sentence, which would be This <i>is</i> a <b>test</b>.

I know how to use .text() to strip out the text, then .indexOf() to find the first period so I know where the first sentence ends, but I don't know how to do all that while keeping the HTML formatting as well. Right now, I've got a really messy solution using regular JavaScript that loops through the nodes and such. However, things start to get a bit messier when I've got <a> links inside <b> for开发者_Python百科matting.


$("#text").mouseover(function(event) {
   alert($(this).html().split(".")[0]+".");
});

Maybe I'm understanding you incorrectly, but it could be as easy as that.


I'm creating a new answer instead of commenting since this is a possible answer to my own question, which I created just now after playing around with this a bit. (As I mentioned earlier, my previous attempt did not involve jQuery and had too many problems, as well.) I'd appreciate feedback, though, since it could probably use some tweaking for specific cases. I'm using an HTML string instead of a jQuery object as input since I need to strip the HTML of <b> tags first, and I just found it easier to use .replace rather than loop through each node to do that. I'll probably get around to fixing that soon.

The following code works pretty well so far. It even finds the first period if it's inside tags, such as a <b>test.</b>, and removes the subsequent nodes accordingly. But, if it's a <b>test. Blah</b> then it will keep the Blah since the code below doesn't currently dig any deeper to properly remove text following the . when it's inside another node.

HTML:

<div id="text">This <i>is</i> a <b>test</b>. Do <i>not</i> be <b>alarmed</b>.</div>

JavaScript:

$('#text').replaceWith(firstSentenceOnly($('#text').html().replace(/<(b|strong)>(.*?)<\/(b|strong)>/gi, '$2')));

function firstSentenceOnly(node)
{
    // Convert to jQuery object
    if (typeof(node) == 'string')
        node = $('<div>' + node + '</div>');

    var periodFound = false;

    node.contents().each(function()
    {
        if (periodFound == true)
        {
            $(this).remove();
        }
        else if ($(this).text().indexOf('.') != -1)
        {
            periodFound = true;

            if ($(this)[0].nodeValue && $(this)[0].nodeValue.indexOf('.') != -1)
            {
                $(this)[0].nodeValue = $(this)[0].nodeValue.substring(0, $(this)[0].nodeValue.indexOf('.') + 1);
            }
        }
    });

    return node;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜