I am not familiar with JavaScript and html. But I tried to implement a function using JavaScript.
I want to replace all <em> and </em> in a html page. So I insert a piece of javascript code in the page:
function rep()
{
document.body.innerHTML
= document.body.innerHTML
.replaceAll("<em>", "_");
document.body.innerHTML
= document.body.innerHTML
.replaceAll("</em>", "_");
}
window.onload=rep()
<!DOCTYPE html>
<html lang="en">
<!-- ... -->
<article>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 post-container">
<p>(Weierstrass) 设 $z_{0}$ 是 $f$ 的本性奇点,那么对任意 $A \in \mathbb{C}<em>{\infty}$, 必存在趋于 $z</em>{0}$ 的点列 $\left{z_{n}\right}$, 使得 $\lim <em>{n \rightarrow \infty} f\left(z</em>{n}\right)=A$.</p>
</div>
</div>
</div>
<!-- ... -->
</html>
It succeeded in replacing <em> with "_", but all </em> did not change. What's wrong with the code?
Thank you!
Let's see what happens when browsers see invalid html like:
test</em>
console.log(document.body.innerHTML)
test</em>
The above prints test (and the script)
That's because the browser strips invalid structures when parsing
When you do
document.body.innerHTML
= document.body.innerHTML
.replaceAll("<em>", "_");
You replace all <em> tags correctly, but the closing tags are removed
This will work on the other hand:
document.body.innerHTML = document.body.innerHTML
.replaceAll("<em>", "_")
.replaceAll("</em>", "_");
<em>test</em>
It maybe better to use the available DOM methods for this.
Pick up all the em elements with querySelectorAll.
For each element create a text node. Bookend the element's original text content with underscores, and add that to the text node. Use replaceWith to replace the em element with the text node.
const ems = document.querySelectorAll('em');
ems.forEach(em => {
const text = `_${em.textContent}_`;
const node = document.createTextNode(text);
em.replaceWith(node);
});
<p>(Weierstrass) 设 $z_{0}$ 是 $f$ 的本性奇点,那么对任意 $A \in \mathbb{C}<em>{\infty}$, 必存在趋于 $z</em>{0}$ 的点列 $\left{z_{n}\right}$, 使得 $\lim <em>{n \rightarrow \infty} f\left(z</em>{n}\right)=A$.</p>
<ul>
<li><em>This is some italised text</em></li>
<li>And this is not.</li>
<li><em>But this is</em>.</li>
</ul>
Additional documentation
querySelectorAll
replaceWith
forEach
Template/string literals
Processing html with regexes or string functions is a bad idea (html is not a string), but if you must, it should be done like this:
let html = document.body.innerHTML
html = html.replace(...)
html = html.replace(...) etc
document.body.innerHTML = html
In other words, do not use a partially processed string to set innerHTML.
Simpler but not efficient:
document.body.innerHTML.replace(/\<em\>|\<\/em\>/gm, '_');
Result:
//body before: <em>test</em>
//body after: _test_
The regex will pass over the entire body and will replace all <em> or </em> occurrences with _
The regex options g for global and m for multiline allow to cover the whole body and multiple occurrences.
Related
I am trying to remove all the html tags out of a string in Javascript.
Heres what I have... I can't figure out why its not working....any know what I am doing wrong?
<script type="text/javascript">
var regex = "/<(.|\n)*?>/";
var body = "<p>test</p>";
var result = body.replace(regex, "");
alert(result);
</script>
Thanks a lot!
Try this, noting that the grammar of HTML is too complex for regular expressions to be correct 100% of the time:
var regex = /(<([^>]+)>)/ig
, body = "<p>test</p>"
, result = body.replace(regex, "");
console.log(result);
If you're willing to use a library such as jQuery, you could simply do this:
console.log($('<p>test</p>').text());
This is an old question, but I stumbled across it and thought I'd share the method I used:
var body = '<div id="anid">some text</div> and some more text';
var temp = document.createElement("div");
temp.innerHTML = body;
var sanitized = temp.textContent || temp.innerText;
sanitized will now contain: "some text and some more text"
Simple, no jQuery needed, and it shouldn't let you down even in more complex cases.
Warning
This can't safely deal with user content, because it's vulnerable to script injections. For example, running this:
var body = '<img src=fake onerror=alert("dangerous")> Hello';
var temp = document.createElement("div");
temp.innerHTML = body;
var sanitized = temp.textContent || temp.innerText;
Leads to an alert being emitted.
This worked for me.
var regex = /( |<([^>]+)>)/ig
, body = tt
, result = body.replace(regex, "");
alert(result);
This is a solution for HTML tag and   etc and you can remove and add conditions
to get the text without HTML and you can replace it by any.
convertHtmlToText(passHtmlBlock)
{
str = str.toString();
return str.replace(/<[^>]*(>|$)| ||»|«|>/g, 'ReplaceIfYouWantOtherWiseKeepItEmpty');
}
Here is how TextAngular (WYSISYG Editor) is doing it. I also found this to be the most consistent answer, which is NO REGEX.
#license textAngular
Author : Austin Anderson
License : 2013 MIT
Version 1.5.16
// turn html into pure text that shows visiblity
function stripHtmlToText(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
var res = tmp.textContent || tmp.innerText || '';
res.replace('\u200B', ''); // zero width space
res = res.trim();
return res;
}
you can use a powerful library for management String which is undrescore.string.js
_('a link').stripTags()
=> 'a link'
_('a link<script>alert("hello world!")</script>').stripTags()
=> 'a linkalert("hello world!")'
Don't forget to import this lib as following :
<script src="underscore.js" type="text/javascript"></script>
<script src="underscore.string.js" type="text/javascript"></script>
<script type="text/javascript"> _.mixin(_.str.exports())</script>
my simple JavaScript library called FuncJS has a function called "strip_tags()" which does the task for you — without requiring you to enter any regular expressions.
For example, say that you want to remove tags from a sentence - with this function, you can do it simply like this:
strip_tags("This string <em>contains</em> <strong>a lot</strong> of tags!");
This will produce "This string contains a lot of tags!".
For a better understanding, please do read the documentation at
GitHub FuncJS.
Additionally, if you'd like, please provide some feedback through the form. It would be very helpful to me!
For a proper HTML sanitizer in JS, see http://code.google.com/p/google-caja/wiki/JsHtmlSanitizer
<html>
<head>
<script type="text/javascript">
function striptag(){
var html = /(<([^>]+)>)/gi;
for (i=0; i < arguments.length; i++)
arguments[i].value=arguments[i].value.replace(html, "")
}
</script>
</head>
<body>
<form name="myform">
<textarea class="comment" title="comment" name=comment rows=4 cols=40></textarea><br>
<input type="button" value="Remove HTML Tags" onClick="striptag(this.form.comment)">
</form>
</body>
</html>
The selected answer doesn't always ensure that HTML is stripped, as it's still possible to construct an invalid HTML string through it by crafting a string like the following.
"<<h1>h1>foo<<//</h1>h1/>"
This input will ensure that the stripping assembles a set of tags for you and will result in:
"<h1>foo</h1>"
additionally jquery's text function will strip text not surrounded by tags.
Here's a function that uses jQuery but should be more robust against both of these cases:
var stripHTML = function(s) {
var lastString;
do {
s = $('<div>').html(lastString = s).text();
} while(lastString !== s)
return s;
};
The way I do it is practically a one-liner.
The function creates a Range object and then creates a DocumentFragment in the Range with the string as the child content.
Then it grabs the text of the fragment, removes any "invisible"/zero-width characters, and trims it of any leading/trailing white space.
I realize this question is old, I just thought my solution was unique and wanted to share. :)
function getTextFromString(htmlString) {
return document
.createRange()
// Creates a fragment and turns the supplied string into HTML nodes
.createContextualFragment(htmlString)
// Gets the text from the fragment
.textContent
// Removes the Zero-Width Space, Zero-Width Joiner, Zero-Width No-Break Space, Left-To-Right Mark, and Right-To-Left Mark characters
.replace(/[\u200B-\u200D\uFEFF\u200E\u200F]/g, '')
// Trims off any extra space on either end of the string
.trim();
}
var cleanString = getTextFromString('<p>Hello world! I <em>love</em> <strong>JavaScript</strong>!!!</p>');
alert(cleanString);
If you want to do this with a library and are not using JQuery, the best JS library specifically for this purpose is striptags.
It is heavier than a regex (17.9kb), but if you need greater security than a regex can provide/don't care about the extra 17.6kb, then it's the best solution.
Like others have stated, regex will not work. Take a moment to read my article about why you cannot and should not try to parse html with regex, which is what you're doing when you're attempting to strip html from your source string.
Here's a sample HTML I have (Actual HTML is pretty big & complex and I am not posting it for the sake of simplicity):
<!DOCTYPE html>
<html>
<head>
</head>
<body style="background-color: #000000;font-family:'Open Sans'">
<div class:'abc' id="cde"></div>
<div class:"abc" id="fed"></div>
<div class:abc id="ce"></div>
<div class:"abc"><p class="content" autocomplete> I am some text which might contain attribute:"invalid value" and I must not be removed</p></div>
</body>
</html>
Goal here is to remove the invalid attributes from the HTML without disturbing the rest of the html. Obviously, the invalid attributes can be anything other than attribute="value", or attribute=value or attribute='value' or even attribute (e.g. <input id="abc" type="text" value="test" disabled>) and the regex should remove it. This content cannot be loaded into DOM so please suggest regex based solutions only.
For starters, I am trying /[a-zA-Z]+:"?'?[a-zA-Z]+"?'?/gi but I know I am nowhere even close!
Here's the fiddle for you to play with.
Expected output:
<!DOCTYPE html>
<html>
<head>
</head>
<body style="background-color: #000000;font-family:'Open Sans'">
<div id="cde"></div>
<div id="fed"></div>
<div id="ce"></div>
<div ><p class="content" autocomplete> I am some text which might contain attribute:"invalid value" and I must not be removed</p></div>
</body>
</html>
Update 1:
The regex should work with any element and not just the divs. divs
were given just for example. it should work with span etc too.
No detection of unclosed tag is needed. We just need to remove attribute:value/attribute;value/attribute:"value" (basically anything other than the valid attributes supported) etc if they are inside <element>.
I'd go with .replace function twice:
var html = `<!DOCTYPE html>
<html>
<head>
</head>
<body style="background-color: #000000;font-family:'Open Sans'">
<div class:'abc' id="cde"></div>
<div class:"abc" id="fed"></div>
<div class:abc id="ce"></div>
<div class:"abc"><p class="content" autocomplete required blah=blah> I am some text which might contain attribute:"invalid value" and I must not be removed</p></div>
</body>
</html>`;
var htmlCleaned = html.replace(/(<\w+)(\s[^>]*)>+/g, function($m, $1, $2) {
return $1 + $2.replace(/\s*?(\s?\w+(?:=(?:'[^'\\]*(?:\\.[^'\\]*)*'|"[^"\\]*(?:\\.[^"\\]*)*"|\w+)|(?!\S)))|\s*\S+/g, '$1') + ">";
});
console.log(htmlCleaned)
Though generally not advisable, you could use two expressions on the DOM, one to filter potentially elements, one to actually eradicate the attributes in question:
var html = `<!DOCTYPE html>
<html>
<head>
</head>
<body style="background-color: #000000;font-family:'Open Sans'">
<div class:'abc' id="cde"></div>
<div class:"abc" id="fed"></div>
<div class:abc id="ce"></div>
<div class:"abc"><p class="content" autocomplete> I am some text which might contain attribute:"invalid value" and I must not be removed</p></div>
<!-- another one here -->
<div class:'abc defg' id="ce"></div>
</body>
</html>`;
var cleaned = html.replace(/<(?:(?!>).)*\b\w+:['"]?\w+['"]?.*?>/g, function(match) {
return match.replace(/\s+\w+:(?:(?:'[^']*')|(?:"[^"]*")|\w+)\s*(?!\w)/g, '');
});
console.log(cleaned);
Broken down, this says for the first expression (demo on regex101.com):
< # <
(?:(?!>).)* # anything where > is not immediately ahead
\b\w+: # a word boundary +1 word characters and :
['"]? # quotes, optional
\w+ # another 1+ word characters
['"]? # as above
.*? # anything else lazily afterwards
> # >
... and for the second (inner) one:
\s+\w+: # 1+ whitespaces, 1+ word characters
(?: # non-capturing group
(?:'[^']*') # '...'
| # or
(?:"[^"]*") # "..."
| # or
\w+ # 1+ word characters
)
\s*(?!\w) # 0+ whitespaces, make sure there's no
# word character ahead
Note that this won't take into account sth. like data-attribute='some weird <> characters here: """'> or data-key="hey, i'am \"escaped, yippeh!">, which are both totally valid.
If you expect such input, really use a parser instead.
This is quite a task that deserves a dedicated library. In order to identify invalid attributes you need to find first the valid tags that is also not that easy and clear. E.g what needs to be done when some tag is not closed? Should the uncloseable tags like input be supposed to be closed? Should href be an attribute of div? Etc etc etc
This is nearly impossible with plain regexp. Even if it will be it won't cover all the cases or will be too complex = unsupportable.
Just give it out to the library that does it for you e.g. this one https://github.com/dave-kennedy/clean-html
This code parses your html splits the relevant parts and checks to see whether the attributes are valid.
You could probably make it more efficient as it's looping multiple times, but this way is easier to understand in it's component parts.
That said. Don't use this code. if you can't parse your element to the DOM figure out a way, if you are in Node you can parse as xml and work with the nodes to ensure everything works correctly.
My little console app doesn't display the autocomplete attribute but it's there in the string.
this code will probably fail in a production environment!
const html = document.querySelector('#input').innerHTML
const isElement = x =>
/^<.*>$/.test(x)
const isValidAttribute = x =>
/^(([a-zA-Z-]+)=?((?:\"|\')[^\'\"]*(?:\"|\'))*|\w+)$/.test(x)
const similarToAttribute = x =>
/=.*((?:\"|\').*(?:\"|\'))/.test(x)
const isOpeningOrClosingBracket = x =>
/(^<|>$)/.test(x)
const output =
html
// .replace(/(\n|\r)+/gm, '') // uncomment to remove new lines
.split(/(<[^>]+>)/) // split the elements
.filter(x => x !== "") // remove empty elements
.map( x => !isElement(x)
? x // it's not an element node, return it
: x.split(/(<\w+|>|\s)/) // split the parts of elements
.filter(x => x !== " " && x !== "") // remove empty elements
.reduce((acc, x) => {
return isOpeningOrClosingBracket(x) || isValidAttribute(x)
? acc.concat(x) // return valid components
: acc // failed check, dont return the attribute
}, [])
)
.map(x => Array.isArray(x) // arrays are elements
? x.slice(0, x.length - 1).join(' ') + x[x.length -1] // join the element string
: x // return anything else
)
.join('') // join the entire array into a string
const div = document.createElement('section')
div.innerHTML = output
console.log(output)
console.log(div)
/* UNIT TESTS */
expect('string is valid element format', () => {
assert(isElement('<div>')).equal(true)
assert(isElement('</div>')).equal(true)
assert(isElement('not an element')).equal(false)
})
expect('string is valid attribute format', () => {
assert(isValidAttribute('class="thing"')).equal(true)
assert(isValidAttribute('class:\'abc\'="thing"')).equal(false)
assert(isValidAttribute('class:\'abc\'="thing"')).equal(false)
assert(isValidAttribute('autocomplete')).equal(true)
})
expect('string has similar properties to an attribute', () => {
assert(similarToAttribute('this is not an attribute')).equal(false)
assert(similarToAttribute('class:\'abc\'="thing"')).equal(true)
assert(similarToAttribute('class:\'abc\'="thing"')).equal(true)
})
expect('string is opening or closing tag', () => {
assert(isOpeningOrClosingBracket('<div')).equal(true)
assert(isOpeningOrClosingBracket('>')).equal(true)
assert(isOpeningOrClosingBracket('class="thing"')).equal(false)
})
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>
<pre id="input">
<div class:'abc' id="cde"></div>
<div class:"abc" id="fed"></div>
<div class:abc id="ce"></div>
<div class:"abc"><p class="content" autocomplete> I am some text which might contain attribute:"invalid value" and I must not be removed</p></div>
</pre>
Use This (?<=(div ))[a-zA-Z]+:"?'?[a-zA-Z]+"?'?
Demo
In jsfiddle
I have string with html code.
<h2 class="some-class">
<a href="#link" class="link" id="first-link"
<span class="bold">link</span>
</a>
NEED TO GET THIS
</h2>
I need to get only text content of h2.
I create this regular expression:
(?<=>)(.*)(?=<\/h2>)
But it's useful if h2 has no inner tags. Otherwise I get this:
<a href="#link" class="link" id="first-link"
<span class="bold">link</span>
</a>
NEED TO GET THIS
Never use regex to parse HTML, check these famous answers:
Using regular expressions to parse HTML: why not?
RegEx match open tags except XHTML self-contained tags
Instead, generate a temp element with the text as HTML and get content by filtering out text nodes.
var str = `<h2 class="some-class">
<a href="#link" class="link" id="first-link"
<span class="bold">link</span>
</a>
NEED TO GET THIS
</h2>`;
// generate a temporary DOM element
var temp = document.createElement('div');
// set content
temp.innerHTML = str;
// get the h2 element
var h2 = temp.querySelector('h2');
console.log(
// get all child nodes and convert into array
// for older browser use [].slice.call(h2...)
Array.from(h2.childNodes)
// iterate over elements
.map(function(e) {
// if text node then return the content, else return
// empty string
return e.nodeType === 3 ? e.textContent.trim() : '';
})
// join the string array
.join('')
// you can use reduce method instead of map
// .reduce(function(s, e) { return s + (e.nodeType === 3 ? e.textContent.trim() : ''); }, '')
)
Reference :
Fastest way to convert JavaScript NodeList to Array?
Rgex is not good for parsing HTML, but if your html is not valid or any way you like to use regex:
(?!>)([^><]+)(?=<\/h2>)
try Demo
It's getting last texts before closing tag of </h2> (IF EXISTS)
To avoid null results changed * to +.
This Regex is completely limit and fitting to limited situations as question mentioned.
demo
var h2 = document.querySelector('h2')
var h2_clone = h2.cloneNode(true)
for (let el of h2_clone.children) {
el.remove()
}
alert(h2_clone.innerText)
Suppose I have an HTML string literal template looking like this:
let tpl =
`<div>
<h1>Hello world</h1>
</div>`;
Once compiled to javascript (es5), it becomes something like:
var tpl = "<div>\n <h1>Hello World</h1>\n </div>
Which takes up uncessary space in generated code. What can I do to make the generated code like this:
var tpl = "<div><h1>Hello World</h1></div>";
OR at least:
var tpl = "<div>" + "<h1>Hello World</h1>" + "</div>";
Without having to actually write this logic in my TypeScript source code?
Template string preserves white spaces.
You need to write your string without the white spaces to begin with.
var tpl = `<div>
<h1>hello world</h1>
</div>`
UPDATE: You can use tagged string template if you want to:
function trimIndent(strings: TemplateStringsArray) {
return str[0].split('\n').map(s => s.trim()).join('')
}
var tpl = trimIndent`<div>
<h1>Hello World</h1>
</div>`
You can improve the function trimIndent() to meet your need.
tpl.replace(/\s/gm, "");
"/\s/gm" is a regular expression which says "for all whitespace, tabs and line breaks", the String.prototype.replace function uses the regex to match all whitespace and linebreaks and replaces them with nothing.
If I have a block of HTML with many tags, how do insert it in JavaScript?
var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
div.innerHTML = 'HERE TOO MUCH HTML that is much more than one line of code';
document.getElementById('posts').appendChild(div);
How do I do it right?
Template literals may solve your issue as it will allow writing multi-line strings and string interpolation features. You can use variables or expression inside string (as given below). It's easy to insert bulk html in a reader friendly way.
I have modified the example given in question and please see it below. I am not sure how much browser compatible Template literals are. Please read about Template literals here.
var a = 1, b = 2;
var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
div.innerHTML = `
<div class="parent">
<div class="child">${a}</div>
<div class="child">+</div>
<div class="child">${b}</div>
<div class="child">=</div>
<div class="child">${a + b}</div>
</div>
`;
document.getElementById('posts').appendChild(div);
.parent {
background-color: blue;
display: flex;
justify-content: center;
}
.post div {
color: white;
font-size: 2.5em;
padding: 20px;
}
<div id="posts"></div>
This answer does not use backticks/template literals/template strings (``), which are not supported by Internet Explorer.
Using HTML + JavaScript:
You could keep the HTML block in an invisible container (like a <script>) within your HTML code, then use its innerHTML at runtime in JS
For example:
// Create a temporary <div> to load into
var div = document.createElement('div');
div.setAttribute('class', 'someClass');
div.innerHTML = document.getElementById('blockOfStuff').innerHTML;
// You could optionally even do a little bit of string templating
div.innerHTML = div.innerHTML
.replace(/{VENDOR}/g, 'ACME Inc.')
.replace(/{PRODUCT}/g, 'Best TNT')
.replace(/{PRICE}/g, '$1.49');
// Write the <div> to the HTML container
document.getElementById('targetElement').appendChild(div);
.red {
color: red
}
<script id="blockOfStuff" type="text/html">
Here's some random text.
<h1>Including HTML markup</h1>
And quotes too, or as one man said, "These are quotes, but
'these' are quotes too."<br><br>
<b>Vendor:</b> {VENDOR}<br>
<b>Product:</b> {PRODUCT}<br>
<b>Price:</b> {PRICE}
</script>
<div id="targetElement" class="red"></div>
Idea from this answer: JavaScript HERE-doc or other large-quoting mechanism?
Using PHP:
If you want to insert a particularly long block of HTML in PHP you can use the Nowdoc syntax, like so:
<?php
$some_var = " - <b>isn't that awesome!</b>";
echo
<<<EOT
Here's some random text.
<h1>Including HTML markup</h1>
And quotes too, or as one man said, "These are quotes, but 'these' are quotes too."
<br><br>
The beauty of Nowdoc in PHP is that you can use variables too $some_var
<br><br>
Or even a value contained within an array - be it an array from a variable you've set
yourself, or one of PHP's built-in arrays. E.g. a user's IP: {$_SERVER['REMOTE_ADDR']}
EOT;
?>
Here's a PHP Fiddle demo of the above code that you can run in your browser.
One important thing to note: The <<<EOT and EOT; MUST be on their own line, without any whitespace before them!
Why use Nowdoc in PHP?
One huge advantage of using Nowdoc syntax over the usual starting and stopping your PHP tag is its support for variables. Consider the normal way of doing it - shown in the example below:
<?php
// Load of PHP code here
?>
Now here's some HTML...<br><br>
Let's pretend that this HTML block is actually a couple of hundred lines long, and we
need to insert loads of variables<br><br>
Hi <?php echo $first_name; ?>!<br><br>
I can see it's your birthday on <?php echo $birthday; ?>, what are you hoping to get?
<?php
// Another big block of PHP here
?>
And some more HTML!
</body>
</html>
Contrast that to the simplicity of Nowdoc.
Despite the imprecise nature of the question, here's my interpretive answer.
var html = [
'<div> A line</div>',
'<div> Add more lines</div>',
'<div> To the array as you need.</div>'
].join('');
var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
div.innerHTML = html;
document.getElementById('posts').appendChild(div);
If I understand correctly, you're looking for a multi-line representation, for readability? You want something like a here-string in other languages. Javascript can come close with this:
var x =
"<div> \
<span> \
<p> \
some text \
</p> \
</div>";
The easiest way to insert html blocks is to use template strings (backticks). It will also allow you to insert dynamic content via ${...}:
document.getElementById("log-menu").innerHTML = `
<a href="#">
${data.user.email}
</a>
<div class="dropdown-menu p-3 dropdown-menu-right">
<div class="form-group">
<label for="email1">Logged in as:</label>
<p>${data.user.email}</p>
</div>
<button onClick="getLogout()" ">Sign out</button>
</div>
`
Add each line of the code to a variable and then write the variable to your inner HTML. See below:
var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
var str = "First Line";
str += "Second Line";
str += "So on, all of your lines";
div.innerHTML = str;
document.getElementById('posts').appendChild(div);
If you are using on the same domain then you can create a seperate HTML file and then import this using the code from this answer by #Stano :
https://stackoverflow.com/a/34579496/2468603
By far the easiest way is to use the insertAdjacentHTML() method.
w3schools article
Just make sure to wrap you LARGE CODE INTO A SINGLE DIV like a wrapper, then it doesn't matter how long it is.
HTML:
<div id='test'></div>
JS:
const arr = ['one', 'two', 'three'];
let mapped = arr.map(value=> {
return `
<div>
<hr />
<h1>${value}</h1>
<h3>this is it</h3>
</div>
`
});
document.querySelector('#test').innerHTML = mapped.join('');