Reputation: 392
I am trying to make an array from string. the string contains HTML tags like P, span, a,img. some are nested like span tag inside p, img tag inside a etc. i would not replace any tags or styles. I am trying to parse all the tags and make an array.
Example code looks like this in textData variable
var line_array =[];
var textData : `
<img src="imgurl" alt="" />
<p>some text</p>
<p style="cssStyle">some text</p>
<span style="cssStyle"> some text </span>
<p style="cssStyle">some text<span style="cssStyle"> span text </span></p>
<a href=""><span style="style">text</span><img src="https://via.placeholder.com/100" alt=""/> </a>
`
activate: function (){
let sourceText = document.getElementById('sourceText').innerHTML;
line_array = sourceText;
}
I am trying to make an array look like this... from textData
line_array =[
'<img src="imgurl" alt="" />',
'<p>some text</p>',
'<p style="cssStyle">some text</p>',
'<span style="cssStyle"> some text </span>',
'<p style="cssStyle">some text<span style="cssStyle"> span text </span</p>',
'<a href=""><span style="style">text</span><img src="imgurl" alt=""/></a>'
]
Upvotes: 1
Views: 786
Reputation: 2394
This is hard or impossible to do with regexp alone (depending on the complexity of HTML that you want/need to allow). You can use split-html.
<script src="https://cdn.jsdelivr.net/npm/[email protected]/index.min.js"></script>
<script>
const textData = `
<img src="imgurl" alt="" />
<p>some text</p>
<p style="cssStyle">some text</p>
<span style="cssStyle"> some text </span>
<p style="cssStyle">some text<span style="cssStyle"> span text
</span></p>
<a href=""><span style="style">text</span><img src="https://via.placeholder.com/100" alt=""/> </a>
`
const line_array = splitHtml(textData, 'img, a, p').filter(String);
console.log(line_array);
</script>
Upvotes: 1