[英]split a html tag by its selection in javascript
想要将标签一分为二。 我有这样的标签
<span class="ss" custom-attr="kk"> split content here, and have to split </span>
如果我选择内容and have
并单击一个按钮,则想分割一个标签。 偶数跨度包含许多属性。 我想与该属性分裂。
<span class="ss" custom-attr="kk"> split content here, </span>and have <span class="ss" custom-attr="kk">to split </span>
我可以使用window.getSelection()
获得选定的文本。 例如: https : //jsfiddle.net/rx5ojfwc/
您可以使用此功能:
function getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return text; }
创建标签并替换内容:
var myNewTag = '</span>' + getSelectionText() + '<span>';
该函数来自用户Tim Down: 获取突出显示/选定的文本
使用jQuery插件,您可以获取选择并执行替换。 它是动态的,因此您甚至不需要知道它是否是<span>
标记。
(function($) { $.getSelectedText = function() { if (window.getSelection) { return window.getSelection().toString(); } else if (document.selection) { return document.selection.createRange().text; } return ''; }; $.fn.spanSelectReplace = function() { var tag = this.prop('tagName').toLowerCase(); var tStart = '<' + tag + '>'; var tEnd = '</' + tag + '>'; var selText = $.getSelectedText(); return this.replaceWith(tStart + this.html().replace(selText, tEnd + selText + tStart) + tEnd); } })(jQuery); $('button').on('click', function() { $('span').spanSelectReplace(); // Perform the jQuery function. console.log($('span').parent().html()); // Print the HTML to the console. });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span>Split content here, and have to split</span> <br /> <button>Split</button>
<span>Split content here, </span>and have<span> to split</span>
在文本区域中突出显示文本的"and have "
部分,然后单击“ 拆分”按钮。
通过将选择内容包装在<span>
标记中来替换文本。
function splitText(button) { var formEl = document.getElementById('content'); var selection = getSelection(formEl); formEl.value = formEl.value.replace(selection, '</span>' + selection + '<span>'); } function getSelection(field) { var start = field.selectionStart; var finish = field.selectionEnd; return field.value.substring(start, finish); }
textarea { width: 100%; }
<textarea id="content" rows="5"><span> split content here, and have to split </span></textarea> <br> <input type="button" value="Split" onClick="splitText(this)" />
您可以非常容易地使用replace()进行此操作。
var str = "<span> split content here, and have to split </span>";
var res = str.replace("here,", "here, </span>");
res = res.replace("have ", "have <span>");
您可以split()和join()以及replace()来实现此目的:
将字符串存储到var中:
var str = "<span> split content here, and have to split </span>";
处理字符串:
str.split(",").join(", </span>").replace("and have", "and have <span>")
var str = "<span> split content here, and have to split </span>"; str.split(",").join(", </span>").replace("and have", "and have <span>") console.log(str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.