Rendering Plaintext as HTML maintaining whitespace – without

前端 未结 4 1729
情深已故
情深已故 2021-02-14 08:02

Given any arbitrary text file full of printable characters, how can this be converted to HTML that would be rendered exactly the same (with the following requirements)?

4条回答
  •  我在风中等你
    2021-02-14 08:15

    The solution to do that while still allowing the browser to wrap long lines is to replace each sequence of two spaces with a space and a non break space.

    The browser will correctly render all spaces (normal and non break ones), while still wrapping long lines (due to normal spaces).

    Javascript:

    text = html_escape(text); // dummy function
    text = text.replace(/\t/g, '    ')
               .replace(/  /g, '  ')
               .replace(/  /g, '  ') // second pass
                                          // handles odd number of spaces, where we 
                                          // end up with " " + " " + " "
               .replace(/\r\n|\n|\r/g, '
    ');

提交回复
热议问题