简体   繁体   English

使用 Javascript 将标签 [start] [end] 包裹在 textarea 中的选定文本周围

[英]Wrap tags [start] [end] around selected text in textarea with Javascript

I have a textarea where users can input text.我有一个文本区域,用户可以在其中输入文本。 With a button, they should be able to wrap a selected text in this textarea with custom tags [start] [end].使用按钮,他们应该能够使用自定义标签 [start] [end] 将选定的文本包装在这个文本区域中。

<button onclick="addTags();">Add Tags to selected Text</button>

<textarea id="user-input" name="user-input" rows="4" cols="50"></textarea>

Example: If the text in the textarea is for example "1 2 3" and user marks "2" and clicks the button the result in the textarea should be "1 [start]2[end] 3".示例:如果文本区域中的文本例如是“1 2 3”并且用户标记“2”并单击按钮,则文本区域中的结果应该是“1 [start]2[end] 3”。

I am trying no to get a piece of javascript to work, that will do this for me.我正在尝试不让 javascript 工作,这将为我做这件事。

I played around with "window.getSelection()".我玩弄了“window.getSelection()”。 So the question is: What is the right approach for my function?所以问题是:我的 function 的正确方法是什么?

function addTags() {
...
}

Cut the text up: before the selection, the selection, after the selection.将文本剪切:选前、选中、选后。 Then reassemble with tags.然后用标签重新组装。

 document.getElementById("add-tag").onclick = () => { let txt = document.getElementById("user-input"); const before = txt.value.substring(0, txt.selectionStart); const sel = txt.value.substring(txt.selectionStart, txt.selectionEnd); const after = txt.value.substring(txt.selectionEnd); txt.value = `${before}[start]${sel}[end]${after}`; };
 <button id="add-tag">Add Tags to selected Text</button> <textarea id="user-input" name="user-input" rows="4" cols="50"></textarea>

TODO: Handle case where nothing is selected.- TODO:处理未选择任何内容的情况。-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM