将标签放在用户突出显示的文本旁边

pan*_*hro 6 javascript jquery

我需要获取用户选择的textarea区域,然后在其<a>周围插入标签.

我使用它来获取用户选择的区域:

var textComponent = document.getElementById('article');
var selectedText;

if (document.selection != undefined)
{
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
}

// Mozilla version
else if (textComponent.selectionStart != undefined)
{
    var startPos = textComponent.selectionStart;
    var endPos = textComponent.selectionEnd;
    selectedText = textComponent.value.substring(startPos, endPos)
}
Run Code Online (Sandbox Code Playgroud)

现在,我知道我可以对用户选择的文本进行字符串搜索并在其周围插入标签,但是如果用户选择的文本在文本中出现两次会发生什么情况,例如.

你好,告别你,再见.

如果用户突出显示他们想要的链接的第二个"你",那么字符串替换肯定会在"你"的每个实例周围放置一个标签.

什么是最好的方法呢?

Tim*_*own 5

您可以使用我的jQuery插件(演示):

$("#article").surroundSelectedText('<a href="foo.html">', "</a>");
Run Code Online (Sandbox Code Playgroud)

或者你可以使用getInputSelection()我在Stack Overflow上发布的函数几次来获取所有主流浏览器中的选择开始和结束字符索引,然后在textarea上进行字符串替换value:

var sel = getInputSelection(textComponent);
var val = textComponent.value;
textComponent.value = val.slice(0, sel.start) +
                      '<a href="foo.html">' +
                      val.slice(sel.start, sel.end) +
                      "</a>" +
                      val.slice(sel.end);
Run Code Online (Sandbox Code Playgroud)