How to preserve whitespace indentation of text enclosed in HTML
 tags excluding the current indentation level of the 
 tag in the document?

后端 未结 11 1472
萌比男神i
萌比男神i 2020-12-02 18:32

I\'m trying to display my code on a website but I\'m having problems preserving the whitespace indentation correctly.

For instance given the following snippet:

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 19:04

    Managed to do this with JavaScript. It works in Internet Explorer 9 and Chrome 15, I haven't tested older versions. It should work in Firefox 11 when support for outerHTML is added (see here), meanwhile there are some custom implementations available on the web. An excercise for the reader is to get rid of trailing indentation (until I make time to finish it and update this answer).

    I'll also mark this as community wiki for easy editing.

    Please note that you'll have to reformat the example to use tabs as indentation, or change the regex to work with spaces.

    
    
        
            Hello, World!
        
        
            
                <html>
                    <head>
                        <title>Hello World Example</title>
                    </head>
                    <body>
                        Hello, World!
                    </body>
                </html>
            
                class HelloWorld
                {
                    public static int Main(String[] args)
                    {
                        Console.WriteLine(&quot;Hello, World!&quot;);
                        return 0;
                    }
                }
            

提交回复
热议问题