gpt4 book ai didi

javascript - 即使与标点符号相邻,也可以在点击时将单词换行,保留标点符号(javascript)

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:42:31 24 4
gpt4 key购买 nike

此问题基于 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+|[.,-\/#!$%\^&\*;:{}=\-_`~()]/)

fiddle :http://jsfiddle.net/b11nxk92/3/

最佳答案

执行命令

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

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

fiddle :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,正则表达式选择三个元素(一个非单词字符或开头)+(我们的单词)+(一个非单词字符或结尾)然后使用 $ 选择保存它的位置。

fiddle :http://jsfiddle.net/b11nxk92/4/

关于javascript - 即使与标点符号相邻,也可以在点击时将单词换行,保留标点符号(javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32995215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com