Javascript 从字符串的两部分创建html

Javascript 从字符串的两部分创建html,javascript,Javascript,我有两条线。第一个看起来像: const scriptsStr = '<script src="/build/lib.min.js"></script>'; const scriptsStr=''; 第二个看起来像: const htmlStr = '<html><head></head><body>Some markup</body></html>'; consthtmlstr='somema

我有两条线。第一个看起来像:

const scriptsStr = '<script src="/build/lib.min.js"></script>';
const scriptsStr='';
第二个看起来像:

const htmlStr = '<html><head></head><body>Some markup</body></html>';
consthtmlstr='somemarkup';
我需要在htmlStr中关闭标记之前粘贴scriptsStr,然后将其放入iframe中。 如何解析htmlStr以找到结束标记

htmlStr.replace(“”,+scriptsStr);
htmlStr.replace('<head>', '<head>' + scriptsStr);
htmlStr.indexOf(“”)
将为您提供结束标记的索引

然后可以使用,以便在此索引处插入
scriptStr

由于字符串不存在拼接,您可以实现它:

String.prototype.splice = function(start, delCount, newSubStr) {
    return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
或者,正如dustytrash所建议的:

htmlStr.replace(“”,+scriptsStr)在打开标记后插入


htmlStr.replace(“”,'scriptsStr+')
在结束标记之前插入。

这将找到结束正文标记的索引,并在该位置插入您的
scriptsStr
字符串

const scriptsStr = '<script src="/build/lib.min.js"></script>';
const htmlStr = '<html><head></head><body>Some markup</body></html>';
const indexToInsert = htmlStr.indexOf('</body>');

const newString = htmlStr.substr(0, indexToInsert) + scriptsStr + htmlStr.substr(indexToInsert);
const scriptsStr='';
const htmlStr='一些标记';
const indexToInsert=htmlStr.indexOf(“”);
const newString=htmlStr.substr(0,indexToInsert)+scriptsStr+htmlStr.substr(indexToInsert);

虽然它可能不会破坏现代浏览器中的站点,但在
头部
正文
之外包含脚本被认为是不好的做法