编程语言
首页 > 编程语言> > Javascript扫描所选单词前后的单词

Javascript扫描所选单词前后的单词

作者:互联网

我正在尝试生成完整的句子,其中使用javascript突出显示了一个单词.

window.getSelection 

给我加亮的单词.我一直在寻找javascript范围的示例,但仍不完全了解如何通过向后移动选择直到找到标点然后再向前直到找到标点来循环.

例:

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.

如果我在上方选择了“ Facebook”一词,则我的最后一个字符串应该是“痴迷者对于Facebook和Twitter这样的网站至关重要.”

更新1:

下面提到的代码有效,但是如果有html标记,则停止.

例:

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.

通过选择上面的“查找”,输出语句是“您可以找到更多令人失望的数字”,而不是“如果您深入到商务部报告中,您可以找到更多令人失望的数字”

在匹配前后如何删除标签?

解决方法:

window.getSelection返回一个Selection对象,您可以从该对象获得Range,该对象又为您提供开始和结束偏移量.其余的很明显:

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]

这适用于FF和Chrome,IIRC,在MSIE中看起来有所不同.有关更多信息,请参见http://msdn.microsoft.com/en-us/library/ie/ms535869%28v=vs.85%29.aspx.

标签:range,getselection,javascript
来源: https://codeday.me/bug/20191201/2080517.html