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

后端 未结 11 1483
萌比男神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条回答
  •  猫巷女王i
    2020-12-02 19:01

    If you're okay with changing the innerHTML of the element:

    Given:

      
        def some_funtion
          return 'Hello, World!'
        end
      
    

    Which renders as:

    
        def some_funtion
          return 'Hello, World!'
        end
    
    

    The following vanilla JS:

    // get block however you want.
    var block = document.getElementById("the-code");
    
    // remove leading and trailing white space.
    var code = block.innerHTML
                    .split('\n')
                    .filter(l => l.trim().length > 0)
                    .join('\n');
    
    // find the first non-empty line and use its
    // leading whitespace as the amount that needs to be removed
    var firstNonEmptyLine = block.textContent
                                 .split('\n')
                                 .filter(l => l.trim().length > 0)[0];
    
    // using regex get the first capture group
    var leadingWhiteSpace = firstNonEmptyLine.match(/^([ ]*)/);
    
    // if the capture group exists, then use that to
    // replace all subsequent lines.
    if(leadingWhiteSpace && leadingWhiteSpace[0]) {
      var whiteSpace = leadingWhiteSpace[0];
      code = code.split('\n')
                 .map(l => l.replace(new RegExp('^' + whiteSpace + ''), ''))
                 .join('\n');
    }
    
    // update the inner HTML with the edited code
    block.innerHTML = code;
    

    Will result in:

      def some_funtion
      return 'Hello, World!'
    end
    

    And will render as:

    def some_funtion
      return 'Hello, World!'
    end
    

提交回复
热议问题