Question

I'm trying to generate the complete sentence in which a word was highlighted using javascript.

window.getSelection 

get me the highlighted word. I have been searching for examples of javascript ranges but still don't fully understand how to loop by moving the selection backwards till a punctuation is found and then forwards till a punctuation is found.

example:

Social media has a fraught relationship with neurosis. Obsessive people are essential to sites like Facebook and Twitter. They add energy and buzz. Their identities get tied up with their avatars, and that in itself makes the sites seem important. They provide much of the content. A study published last fall reported that twenty thousand users on Twitter provide half of what’s read there. But obsessives are dangerous, too. They can make the site seem creepy.

if I selected the word "Facebook" above, my final string should be "Obsessive people are essential to sites like Facebook and Twitter."


Update 1:

the code mentioned below works but stops if there are html tags.

Example:

If you delve into the Commerce Department report, you can find some even more disappointing numbers. Setting aside the production of inventories—goods that companies add to their stockpiles in anticipation of selling them later—the economy grew by just 1.6 per cent in the quarter. Capital investment, which should be surging at this point in the recovery, hardly rose at all. And personal disposable income—the amount of money people have to spend after paying taxes—expanded by just 0.4 per cent.

by selecting "find" above, the output sentence is "you can find some even more disappointing numbers" instead of "If you delve into the Commerce Department report, you can find some even more disappointing numbers"

how would I remove tags while matching before and after?

Était-ce utile?

La solution

window.getSelection returns a Selection object, from which you can obtain a Range, which, in turn, provides you with start and end offsets. The rest is obvious:

rng = window.getSelection().getRangeAt(0)
start = rng.startOffset
end = rng.endOffset
text = rng.startContainer.nodeValue

before = text.substr(0, start)
sel = text.substr(start, end - start)
after = text.substr(end)

sentence = before.match(/[^.!?]*$/)[0] +  sel + after.match(/^[^.!?]*/)[0]

This works in FF and Chrome, IIRC, things look different in MSIE. See http://msdn.microsoft.com/en-us/library/ie/ms535869%28v=vs.85%29.aspx for more info.

Autres conseils

I'm working on exactly this for my Rangy library and am very close to an initial release. Here's a work-in-progress demo:

http://rangy.googlecode.com/svn/trunk/demos/textrange.html

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top