Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Javascript to get the Sentence of a Clicked Word

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.

like image 997
freedomflyer Avatar asked Nov 14 '12 20:11

freedomflyer


3 Answers

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.

like image 74
Denys Séguret Avatar answered Nov 20 '22 09:11

Denys Séguret


First of all, be prepared to accept a certain level of inaccuracy. This may seem simple on the surface, but trying to parse natural languages is an exercise in madness. Let us assume, then, that all sentences are punctuated by ., ?, or !. We can forget about interrobangs and so forth for the moment. Let's also ignore quoted punctuation like "!", which doesn't end the sentence.

Also, let's try to grab quotation marks after the punctuation, so that "Foo?" ends up as "Foo?" and not "Foo?.

Finally, for simplicity, let's assume that there are no nested tags inside the paragraph. This is not really a safe assumption, but it will simplify the code, and dealing with nested tags is a separate issue.

$('p').each(function() {
    var sentences = $(this)
        .text()
        .replace(/([^.!?]*[^.!?\s][.!?]['"]?)(\s|$)/g, 
                 '<span class="sentence">$1</span>$2');
    $(this).html(sentences);
});

$('.sentence').on('click', function() { 
    console.log($(this).text()); 
});​

It's not perfect (for example, quoted punctuation will break it), but it will work 99% of the time.

  • Live demo: http://jsfiddle.net/SmhV3/
  • Slightly amped-up version that can handle quoted punctuation: http://jsfiddle.net/pk5XM/1/
like image 32
Justin Morgan Avatar answered Nov 20 '22 10:11

Justin Morgan


  1. Match the sentences. You can use a regex along the lines of /[^!.?]+[!.?]/g for this.
  2. Replace each sentence with a wrapping span that has a click event to alert the entire span.
like image 2
just.another.programmer Avatar answered Nov 20 '22 09:11

just.another.programmer