删除选定文本javascript前后的特定文本
Delete particular Text before and after the selected text javascript
我想删除所选文本前后的一些特定文本。例如,如果文本为:
<p>This is a <random>sentence</random> that i am writing<p>
如果用户选择文本,则应该删除<random>和<随机>从文本和文本将是这样的。
This is a sentence that i am writing.
如果用户选择了"句子"以外的任何内容,则不会发生任何事情。我知道如何选择特定的文本,但我不知道下一步如何删除特定文本前后的文本。有可能吗?
function replaceSelection() {
var sel, range, fragment;
if (typeof window.getSelection != "undefined") {
// IE 9 and other non-IE browsers
sel = window.getSelection();
// Test that the Selection object contains at least one Range
if (sel.getRangeAt && sel.rangeCount) {
// Get the first Range (only Firefox supports more than one)
range = window.getSelection().getRangeAt(0);
var selectedText = range.toString();
var replacementText = selectedText.replace(/<'/?random>/, '');
range.deleteContents();
// Create a DocumentFragment to insert and populate it with HTML
// Need to test for the existence of range.createContextualFragment
// because it's non-standard and IE 9 does not support it
if (range.createContextualFragment) {
fragment = range.createContextualFragment(replacementText);
} else {
// In IE 9 we need to use innerHTML of a temporary element
var div = document.createElement("div"), child;
div.innerHTML = replacementText;
fragment = document.createDocumentFragment();
while ( (child = div.firstChild) ) {
fragment.appendChild(child);
}
}
var firstInsertedNode = fragment.firstChild;
var lastInsertedNode = fragment.lastChild;
range.insertNode(fragment);
if (selectInserted) {
if (firstInsertedNode) {
range.setStartBefore(firstInsertedNode);
range.setEndAfter(lastInsertedNode);
}
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE 8 and below
range = document.selection.createRange();
var selectedText = range.text;
var replacementText = selectedText.replace(/<'/?random>/, '')
range.pasteHTML(replacementText);
}
}
<div onmouseup="replaceSelection()"><p>This is a <random>sentence</random> that i am writing<p></div>
相关文章:
- Servlet对浏览器上显示的纯文本Javascript的响应
- 删除选定文本javascript前后的特定文本
- 在两个括号内插入文本 - Javascript
- 获取文本javascript+iframe
- 语音到文本JavaScript,HTML5
- 使用谷歌融合表格地图的网页文本/JavaScript未显示
- 在显示和隐藏文本(javascript)之间切换
- 使用哈希标记保存文本(Javascript - PHP - MySQL)
- 停止闪烁文本 JavaScript
- 如何计算一个字母在文本javascript中出现的次数
- 有效地突出显示文档中的文本 (JavaScript)
- 将变量传递给文本 javascript
- 如何暂停文本 Javascript / var textarray
- 从段落中搜索文本 - Javascript
- 如何使用 id 输入类型=“文本”JavaScript 中的值设置自动 2 个十进制数
- 替换文本 JavaScript .append()
- 语音到文本JavaScript识别医学词典
- 在提取的文本 JavaScript 中搜索关键字
- 如何在HTML中将文本javascript显示为正常正文的一部分
- 单击图像时更改段落文本(Javascript)