For this task i need to update the src attribute on only iframe elements in a string of text that may contain other html elements. The src attribute needs to be replaced with data-src and the attribute cookieconsent="marketing" must also be added.
The JS code is being run on each change of a RTE webressource in a Dynamics CRM system. I currently have the following solution:
CKEDITOR.instances.editor1.on('change',
function () {
var value = CKEDITOR.instances.editor1.getData();
const regex = new RegExp('<iframe[^>]*src="([^"] )"[^>]*>');
const matches = value.match(regex);
value = matches.replace("src=", "cookieconsent=\"marketing\" data-src=")
});
But this select the entire iframe element as well as the value of the src attribute. I need to replace only the "src" part with the new attribute name and add the cookieconsent part.
I'm struggling to come up with a solution that allows me to replace all instances of the src attribute. I can't simply do a replace of "src" in the string, as only iframe elements should be updated.
What expression would work in this instance? Is regex really the best tool for this, or is there an alternative solution? I'm open to ideas.
CodePudding user response:
this tools can help you to get any regexp : https://regex101.com/