Reputation: 520
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.
Upvotes: 0
Views: 211
Reputation: 19212
The problem is that Javascript String.replace()
only works like you expect when using it with a RegExp pattern with the global flag set. Luckily, this answer has a nice solution.
Change this:
iframe.contentDocument.body.innerHTML = iframeContent.replace(iframeSelection,aTag);
...into this:
iframe.contentDocument.body.innerHTML = iframeContent.replace( new RegExp(iframeSelection, 'g'), aTag );
What it does is that it converts your search string into a RegExp object with the global flag set, so each occurrence gets replaced.
If your intention was to only replace the exact piece the user had selected it gets more complex, but you can find all the required bits from this answer.
Upvotes: 0
Reputation: 5982
The problem is that iframeSelection
in your replace()
call is "click", not the element you previously selected, so it's replacing the first occurence.
Instead, try getting the range of your selection, deleting it and appending your new element to that range.
var selection = iframe.contentWindow.getSelection();
range = selection.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createElement(your_new_element));
I couldn't test without your HTML, a JSFiddle would help.
Upvotes: 1