第一句拆分段落

时间:2012-11-08 23:25:23

标签: jquery regex text-segmentation

我有这个div,我想在第一句话中添加一些风格。

<div class="text">dfgdfg.asdhasd</div>

我正在尝试使用此代码但未按预期工作。

var text = $('.text').html().split(".")[0]+".";

$(".text:contains("+text+")").css("color", "red");

DEMO

2 个答案:

答案 0 :(得分:2)

请参阅http://jsfiddle.net/wp5kw/

假设一段:

<p id="para"> This is a test. Is it? Yes, it is indeed! 
You might ask, is this a sentence? To which I would reply 
with a resounding "YES"!!!</p>

要抓住所有句子,请使用:

var sentences=$('#para').text() // get example text
        .match(/[^\.\!\?]+[\.\!\?]+/g) // extract all sentences
        .map(function(s){ // (optional) remove leading and trailing whitespace
            return s.replace(/^\s+|\s+$/g,'');
        });

要突出显示第一句话,请使用:

var count=0;
$('#para2').html(
    $('#para')
        .text()
        .match(/[^\.\!\?]+[\.\!\?]+/g)
        .map(function(s){
            s=s.replace(/^\s+|\s+$/g,'');
            return count++
                ? s
                : '<span style="color:red">'+s+'</span>'
        }).join(' ')
);

正则表达式假设句号,感叹号和问号用于终止句子,并且是:

[^\.\!\?]+         -- one or more non-sentence terminals
[\.\!\?]+          -- followed by one or more sentence terminals

答案 1 :(得分:0)

您需要将其包装在元素中,不能将css应用于文本节点:

var $div = $('.text');
var text = $div.text();

$div.html( text.replace(/.+?\./, '<span>$&</span>') );

演示: http://jsbin.com/ezojic/1/edit