Use Javascript to get the Sentence of a Clicked Word

后端 未结 5 2076
甜味超标
甜味超标 2021-02-05 21:37

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 a         


        
相关标签:
5条回答
  • 2021-02-05 21:58
    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.
    0 讨论(0)
  • 2021-02-05 22:04

    I suggest you take a look at Selection and ranges in JavaScript.

    There is not method parse, which can get you the current selected setence, so you have to code that on your own...

    A Javascript library for getting the Selection Rang cross browser based is Rangy.

    0 讨论(0)
  • 2021-02-05 22:16

    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.

    0 讨论(0)
  • 2021-02-05 22:16

    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/
    0 讨论(0)
  • 2021-02-05 22:20

    Not sure how to get the complete sentense. but you can try this to get word by word if you split each word by spaces.

         <div id="myDiv" onmouseover="splitToSpans(this)" onclick="alert(event.target.innerHTML)">This is a test paragraph. I love cats. Please apply here</div>
    function splitToSpans(element){
        if($(element).children().length) 
            return;
        var arr = new Array();
        $($(element).text().split(' ')).each(function(){
        arr.push($('<span>'+this+' </span>'));
        });
        $(element).text('');
        $(arr).each(function(){$(element).append(this);});
    }
    
    0 讨论(0)
提交回复
热议问题