I'm using the following code to parse html, This code is working but since I'm new to JavaScript and working in alone project I would appreciate if you can give me some tips and feedback how can I improve this code,or it is fine...
The requirements are:
- Insert a new script after given script ID(in the code after test-ui-bootstrap')
- For given script ID update attribute value (when the key is given)
code need to update script content after existing script with new content. The code is working and I use part of it from SO past post
https://jsfiddle.net/st6xg7Lj/1/
Here is the code to convert and convert back
function parseHtml(html) {
// replace html, head and body tag with html_temp, head_temp and body_temp
html = html.replace(/<!DOCTYPE HTML>/i, '<doctype></doctype>');
html = html.replace(/(<\/?(?:html)|<\/?(?:head)|<\/?(?:body))/ig, '$1_temp');
// wrap the dom into a <container>: the html() function returns only the contents of an element
html = "<container>"+html+"</container>";
var element = $(html); // parse the html
return element;
}
function convertBackToHtml(element) {
// reset the initial changes (_temp)
var extended_html = element.html();
extended_html = extended_html.replace(/<doctype><\/doctype>/, '<!DOCTYPE HTML>');
extended_html = extended_html.replace(/(<\/?html)_temp/ig, '$1');
extended_html = extended_html.replace(/(<\/?head)_temp/ig, '$1');
extended_html = extended_html.replace(/(<\/?body)_temp/ig, '$1');
// replace all " inside data-something=""
while(extended_html.match(/(<.*?\sdata.*?=".*?)(")(.*?".*?>)/g)) {
extended_html = extended_html.replace(/(<.*?\sdata.*?=".*?)(")(.*?".*?>)/g, "$1'$3");
}
return extended_html;
}
Here is the code to create new script with content and update the values
var html = $('textarea.input').val();
// parse the html to an element
var element = parseHtml(html);
// do your calculations on the parsed html
$("<script>alert(\"test\");<\/script>").insertAfter(element.find('#test-ui-bootstrap'));
element.find("#test-ui-bootstrap").attr('data-test-ui-libs123', "test.bbb");
element.find("#test-ui-bootstrap").attr('src', 'resources/aaaa/test-ui-core.js');
// convert the element back to html
var extended_html = convertBackToHtml(element);
Since I need to run this code in production very soon and Im fairly new In JS I'd like to get your feedback,I really need it.
The code itself is working OK