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.
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.
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.
/[^!.?]+[!.?]/g
for this.span
that has a click event to alert the entire span.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With