在 JavaScript 中通过选择来拆分 HTML 标记



想要将标签拆分为两。我有这样的标签

<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:获取突出显示/选定的文本

HTML 版本

使用 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>");

退房: https://www.w3schools.com/jsref/jsref_replace.asp

你可以 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);

最新更新