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.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...