如何替换同一索引处的文本。此文本可能具有相同的模式。假设我想在下一个文本中替换粗体“是”。
“山姆是个男孩,多莉是他的妹妹,但约翰是他的父亲。他不是医生。”
当我使用以下代码时,它会替换第一个模式,即斜体“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 代码,反之亦然