If you only have the HTML available as a string, and not as a DOM-document, you can do simple insertions prior to the head-close tag without resorting to regexes. The following code makes use of the splice method in this answer. It could be made a function instead of a prototype, and have the second parameter removed for our purposes:
String.prototype.splice = function( idx, rem, s ) {
return (this.slice(0,idx) + s + this.slice(idx + Math.abs(rem)));
};
var insertTag = function(newTag, html) {
var end = html.indexOf('</head>');
return html.splice(end, 0, newTag);
}
So if you had
var doc = '<head><title>Html</title></head>';
and you ran
var doc = insertTag('<script src="some_path.js"></script>', doc);
You would get
<head><title>Html</title><script src="some_path.js"></script></head>
The function is simple, and doesn't check for existence of the head-close tag, or any other safety concerns that might need to be taken. It would would with line-breaks, and is just given as a general idea of how to avoid DOM (per question) and regexes (per saving your sanity).
However, if you have a DOM available -- use it.
<head>is a tag just like any other in page...no need for regex. You can append to it