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> 
4
  • you mean doing it in the developer console or... do you want to display it on the webpage or what's your purpose? Commented Jan 8, 2020 at 5:13
  • 1
    See RegEx match open tags except XHTML self-contained tags Commented Jan 8, 2020 at 5: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 ... Commented Jan 8, 2020 at 5: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. Commented Jan 20, 2020 at 0:24

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Upvote! I'm wrong when thinking this question is about: Converting string to node in javascript. lol
How to use in angular platforms
Yup.. I 've found it for adding it in the angular platform(stackoverflow.com/questions/46753490/…). :)
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, <div /> is just a start tag, div elements aren't void elements so must have start and end tag. <img /> is a better example, though the / is redundant and <img> is sufficient (HTML start tags).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.