微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何扩展所选文本以包含整个单词

让我说我有一句话:“这是一个测试句.”我希望用户能够选择文本的子部分,但没有标点符号或不完整的单词.

所以“测试句子”.应该成为“测试句”
而“est sentenc”也应成为“测试句”

这是我目前的代码

var getSelectedText = function() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString().trim();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createrange().text;
    }
    return text;
}

fyi:jQuery代码没问题.

编辑Bender:

好的,这几乎就在那里.我有超过50k的句子,用户选择是可变的,所以我必须做这样的事情:

var selection = getSelectedText();
var exp = new RegExp("\\w*" + selection + "\\w+");
text.match(exp);

但是,如果用户选择“测试句子”,则不会匹配.

解决方法

有趣的挑战.

下面的代码将选择包含在选定类的范围内.

它抓取prevIoUsSibling的nodeValue和new元素的nextSibling – 通过拆分非单词字符,弹出(prevIoUsSibling)或shift(nextSibling)来获取相应的文本.

然后删除选定的跨度(同时保留其内容).这必须在超时内完成,以便元素有时间添加到DOM.

此时,我们留下了三个相邻的文本节点.代码通过在文档正文上调用normalize()来加入它们.

$(document).mouseup(function() {
  alert(getSelectedText());
});

var getSelectedText = function() {
  var el= document.createElement('span'),sel= window.getSelection().getRangeAt(0),prev= '',next= '';
  
  el.className= 'selected';
  sel.surroundContents(el);
  if(!sel.toString().match(/^\W/)) {
    prev= el.prevIoUsSibling.nodeValue;
    if(prev.match(/\W$/)) {
      prev= '';
    }
    else {
      prev= prev.split(/\W/).pop();
    }
  }
  if(!sel.toString().match(/\W$/)) {
    next= el.nextSibling.nodeValue;
    if(next.match(/^\W/)) {
      next= '';
    }
    else {
      next= next.split(/\W/).shift();
    }
  }
  setTimeout(function() {
    $('.selected').contents().unwrap()
    $('.selected').remove();
    document.body.normalize();
  });
  return prev+sel.toString()+next;
}
.selected {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is a test sentence.  Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,sunt in culpa qui officia deserunt mollit anim id est laborum.

原文地址:https://www.jb51.cc/js/156963.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐