【问题标题】:Wrap word in span on click even if adjacent to punctuation, retaining punctuation (javascript)即使与标点符号相邻,在点击时将单词换行,保留标点符号(javascript)
【发布时间】:2015-10-07 14:39:50
【问题描述】:

此问题建立在How to wrap word into span on user click in javascript 中提供的答案之上。

在我的示例中,用户可以双击任何单词以将其包装在 span 元素中,但是 b/c 这是基于空格分割的,如果单词后面跟着标点符号,它将不起作用。

HTML:

<div class="color-coding">
  <span class="orange color-coding">Hello world this is some text.</span>
  <br>
  <span class="orange color-coding">Here is some more!</span>
</div>

JS:

jQuery(document).ready(function($) {

$('.color-coding').dblclick(function(e) {

var range = window.getSelection() || document.getSelection() || document.selection.createRange();
var sword = $.trim(range.toString());
if(sword.length)
{

  var newWord = "<span class='highlight'>"+sword+"</span>";

  $(this).each(function(){
      $(this).html(function( _, html ) {
    return html.split(/\s+/).map(function( word ) {
      return word === sword ? newWord : word;
    }).join(' ');
  });
  });
}
range.collapse();
e.stopPropagation();
});

});

我可以为拆分添加标点符号检测,但这当然会删除标点符号,我需要保留它,因此使用以下内容无法满足我的需求:

html.split(/\s+|[.,-\/#!$%\^&\*;:{}=\-_`~()]/)

小提琴:http://jsfiddle.net/b11nxk92/3/

【问题讨论】:

    标签: javascript jquery regex


    【解决方案1】:

    执行命令

    常青浏览器的完美解决方案:

    if(sword.length) {
        this.setAttribute('contenteditable','true');
        document.execCommand("insertHTML", false, "<span class='highlight'>"+sword+"</span>");
        this.removeAttribute('contenteditable');
    }
    

    此解决方案将容器切换到可编辑模式,然后触发插入新 html 代码的命令。请参阅:https://msdn.microsoft.com/en-us/library/hh801231(v=vs.85).aspx#inserthtmlhttps://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

    小提琴:http://jsfiddle.net/b11nxk92/6/

    正则表达式

    另外,我喜欢RegExp,所以我提出了这个解决方案。

    if (sword.length) {
    
        $(this).each(function(){
            $(this).html(function( _, html ) {
                return html.replace(
                    new RegExp("([^\\w]|^)("+sword+")([^\\w]|$)","g"),
                    "$1<span class='highlight'>$2</span>$3"
                );
            });
        });
    }
    

    而不是使用split 然后join 正则表达式选择三个元素(非单词字符或开头)+(我们的单词)+(非单词字符或结尾)然后使用$ you选择保存它的位置。

    小提琴:http://jsfiddle.net/b11nxk92/4/

    【讨论】:

    • 太棒了!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    • 2015-03-04
    相关资源
    最近更新 更多