LENide300_KK
LENide300_KK

Reputation: 25

Grab first two sentences (untill second dot) of a text string with jQuery?

I have this HTML (as an example - Texts can vary in length):

<p>Stockholm is a city in Sweden. Moscow is a city in Russia. Here is Berlin, it's the capital of Germany.</p>

I want to grab the first two sentences of this text and extract them, using JavaScript/jQuery. Further more I also want to extract the rest of the text and put this into its own element.

So basically i want to end up with the following:

<p>Stockholm is a city in Sweden. Moscow is a city in Russia.</p>

and

<p>Here is Berlin, it's the capital of Germany.</p>

So far I am only able to get the first sentence of the text using the following:

var addy = jQuery('#myDiv > p').html();
var introText = addy.slice(0, addy.indexOf("."));

This puts out: "Stockholm is a city in Sweden" - Without the dot aswell. I would also like to have this included.

As stated in the intro, the texts are dynamic and vary in length.

How can I achieve the above?

Thanks in advance!

Upvotes: 2

Views: 1193

Answers (2)

Ram
Ram

Reputation: 144659

One option is:

$('#myDiv > p').each(function() {
   var ss = this.textContent.split('.');
   var f = ss.slice(0, 2).join('.');
   var s = ss.slice(2).join('.');

   $(this).text(f);
   $('<p>').text(s).insertAfter(this);
})

http://jsfiddle.net/0xh5ku4f/

Upvotes: 1

Luca Kiebel
Luca Kiebel

Reputation: 10096

You can use a function to get the second index at which there is a dot, and then split the string at that index:

let str = "<p>Stockholm is a city in Sweden. Moscow is a city in Russia. Here is Berlin, it's the capital of Germany.</p>"

let index = nthIndex(str, ". ", 2);

let parts = [str.substring(0, index+1)+"</p>" ,"<p>"+str.substring(index+2)]

console.log(parts)

function nthIndex(str, pat, n){
    var L= str.length, i= -1;
    while(n-- && i++<L){
        i= str.indexOf(pat, i);
        if (i < 0) break;
    }
    return i;
}

Upvotes: 0

Related Questions