Question

I have this div, and i want to add some style to the first sentence.

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

I am trying this code but is not working as expected.

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

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

DEMO

Was it helpful?

Solution

This is only going to work if there is only one .text element on the page.

var elem = $('.text');
var textParts = elem.html().split(".");
var first = "<span class='red'>" + textParts.shift() + ".</span>";
elem.html(first + textParts.join("."));

If there are multiple it will need an each loop.

var elems = $('.text');
elems.each( function(){
    var elem = $(this);
    var textParts = elem.html().split(".");
    var first = "<span class='red'>" + textParts.shift() + ".</span>";
    elem.html(first + textParts.join("."));
});

Of course this uses a class to set the color, basic class would be

.text .red{
    color: #FF0000;
}

Running example: http://jsfiddle.net/a68dS/1/

OTHER TIPS

See http://jsfiddle.net/wp5kw/

Assuming a paragraph of:

<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>

To grab all the sentences, use:

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

To highlight the first sentence, use:

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

The regular expression assumes that periods, exclamation and question marks are used to terminate a sentence, and is:

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

You need to wrap it in an element, you can't apply css to text nodes:

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

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

Demo: http://jsbin.com/ezojic/1/edit

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top