There are a lot of question about this topic on SO but i can't seem to find any solution for my problem so i decide to ask my question. My situation is i have a dropdown list with several option and a textarea inside iframe
. When user select some text in the textarea and choose one option from dropdown list then the selected text will have an a
tag wrap around it and the option value will become tag href
. Here my code:
var optionTag = document.getElementById("option-id");
var optionValue = optionTag.options[optionTag.selectedIndex].value;
var iframe = document.getElementById("my-frame");
var iframeContent = iframe.contentDocument.body.innerHTML.split("<br>")[0];
//get user selected text
var iframeSelection = iframe.contentWindow.getSelection().toString();
// and wrap a tag around it then add href equal to value of option
var aTag = "<a href=\"" + optionValue + "\">" + iframeSelection +"</a>";
// replace user selected text with new a tag
iframe.contentDocument.body.innerHTML = iframeContent.replace(iframeSelection,aTag)
This code work but it only replace the first word if that word already exist. For example:
lorem ipsum click dolor sit amet click spum
If user select the second word "click" and choose one option then my code will replace the only the first word "click" and if i have several word "click" it still only replace the first word, but if user select the word "ipsum" or "lorem" then it work fine. I don't know how to fix this please help. Thank!
p/s: I don't want to replace all the "click" word, i only want to replace exact piece user selected.