如何替换同一索引处的文本。此文本可能具有相同的模式。假设我想在下一个文本中替换粗体“is”。
当我使用下面的代码时,它取代了第一个用斜体“是”的模式!
function getSelectedHTMLText() {
if (window.getSelection) { // all browsers, except IE before version 9 contents
var range = window.getSelection ();
var container = document.createElement("div");
for (var i = 0, len = range.rangeCount; i < len; ++i) {
container.appendChild(range.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
return html;
}
else {
if (document.selection.createRange) { // Internet Explorer
var range = document.selection.createRange();
html = range.htmlText;
return html;
}
}
}
var txt = "Sam is a boy and Dory is his sister, but John <b>is</b> his father. He isn't a doctor.";
var htmlText = getSelectedHTMLText(); //This return s
var txtModified = txt.replace(htmlText, "is");
注意:我使用此代码将HTML代码替换为非HTML代码,反之亦然
答案 0 :(得分:1)
Tim Down回答了你的问题的答案here。看起来与你的代码非常相似。
我做了一个小提示来证明http://jsfiddle.net/DggQL/它也适用于你的情况。
这是代码
/* taken from https://stackoverflow.com/a/3997896*/
function replaceSelectedText(replacementText) {
var sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(replacementText));
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.text = replacementText;
}
}