Alex Rivera | Logout

Use Javascript to get the Sentence of a Clicked Word

Asked 2012-11-14T20:38:52.853
13

This is a problem I'm running into and I'm not quite sure how to approach it.

Say I have a paragraph:

"This is a test paragraph. I love cats. Please apply here"

And I want a user to be able to click any one of the words in a sentence, and then return the entire sentence that contains it.

Edit
Report

1 Answer

11

You first would have to split your paragraph into elements, as you can't (easily) detect clicks on text without elements :

$('p').each(function() {
    $(this).html($(this).text().split(/([\.\?!])(?= )/).map(
      function(v){return '<span class=sentence>'+v+'</span>'}
   ));
});

Note that it splits correctly paragraphs like this one :

<p>I love cats! Dogs are fine too... Here's a number : 3.4. Please apply here</p>​

Then you would bind the click :

$('.sentence').click(function(){
    alert($(this).text());
});

Demonstration

I don't know if in English : is a separator between sentences. If so, it can be added to the regex of course.

answered 2012-11-14T20:41:52.500

Your Answer