0

How to replace a text at a the same index. This text may have the same pattern. Say I want to replace the bold "is" in the next text.

"Sam is a boy and Dory is his sister, but John is his father. He isn't a doctor."

when I use the following code it replaces the first pattern which is the italicized "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");

Note: I use this code to replace an HTML code with none-HTML code and vice versa

Develop Smith
  • 146
  • 1
  • 3
  • 13
  • Prepare a jsfiddle example. It will be much easier to help you. – Eru Feb 02 '13 at 19:25
  • "`replace the bold "is"`", replace "the bold is" with what? Remove the `b` tag surrounding "is"? – Teemu Feb 02 '13 at 20:16
  • I myself am a big fan of using native JS, but any reason to _not_ use jQuery in this case? – contactmatt Feb 02 '13 at 20:49
  • @Teemu, I know that I have to remove the 'b' but how to get the right one. When I execute the code it deals with the first matching of the text. Imagine that I have more than one "is" surrounded by 'b' tag. – Develop Smith Feb 02 '13 at 21:15
  • @contactmatt, can you help me with the jQuery code that can do my need ? – Develop Smith Feb 02 '13 at 21:16

1 Answers1

1

The answer to your question was answered here by Tim Down. Looks very similar to your code actually.

I made a fiddle to demonstrate http://jsfiddle.net/DggQL/ it's working also in your case.

This is the code

/* 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;
   }
}
Community
  • 1
  • 1
gert vaartjes
  • 988
  • 5
  • 8
  • Thanks gert vaartjes this looks very helpful. I will try it tomorrow as I can't see any more. Thanks for you and for @TimDown. – Develop Smith Feb 02 '13 at 22:20