1

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>'
]

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.