0

The result of my innerHTML is like below in javascript.

"<ol><li>Testing1</li><li>Testing2</li></ol>"

Can I align it in a code format as below using regex or anyother? any suggestion on this ?

<ol>
  <li>Testing1</li>
  <li>Testing2</li>
</ol>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
INDRA JITH
  • 133
  • 1
  • 10
  • you mean doing it in the developer console or... do you want to display it on the webpage or what's your purpose? – nonopolarity Jan 08 '20 at 05:13
  • 1
    See [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – RobG Jan 08 '20 at 05:26
  • As long as your code is properly formatted in the actual file you're working with, you should not concern about formatting the code rendered on the client-side. It's just waste of time ... – Teemu Jan 08 '20 at 05:27
  • This is not a duplicate of that question - that question is about how to *wrap elements, attributes and values with spans with their own classes.*. This is something pretty different. – CertainPerformance Jan 20 '20 at 00:24

1 Answers1

3

The problem isn't trivial. One issue with regular expressions is that Javascript's can't handle nested matching delimiters in most cases. Another issue is that you need to keep track of self-closing tags (<div />, or tags which don't have closing tags (<img>, <input>) and programmatically identify whether the text you're currently processing is part of structured HTML markup, or whether it's just plain text (like <textarea>foo<div>bar</div></textarea>).

It would probably be easier to use a library designed for this purpose, so as not to re-invent the wheel. js-beautify is one option:

const input = "<ol><li>Testing1</li><li>Testing2</li></ol>";
console.log(html_beautify(input, { 'indent-size': 2 }));
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.10.2/beautify-html.js"></script>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Upvote! I'm wrong when thinking this question is about: Converting string to node in javascript. lol – Tân Jan 08 '20 at 04:46
  • How to use in angular platforms – INDRA JITH Jan 08 '20 at 11:06
  • Yup.. I 've found it for adding it in the angular platform(https://stackoverflow.com/questions/46753490/angular-not-able-to-import-library). :) – INDRA JITH Jan 08 '20 at 11:59
  • The main problem is that HTML isn't a regular language, so not really suitable for parsing by regular expressions alone, though they can be useful for identifying tokens. :-) BTW, `
    ` is just a start tag, div elements aren't void elements so must have start and end tag. `` is a better example, though the `/` is redundant and `` is sufficient ([*HTML start tags*](https://html.spec.whatwg.org/multipage/syntax.html#start-tags)).
    – RobG Jan 19 '20 at 23:36