-
Notifications
You must be signed in to change notification settings - Fork 0
/
testing-plaintext-html-gilly3.html
62 lines (59 loc) · 1.8 KB
/
testing-plaintext-html-gilly3.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Testing Solution</title>
<style type="text/css">
body {color: black; background: white;}
.grey {
color: #888;
}
</style>
</head>
<body>
<h1>Testing Solution</h1>
Running <a href="//stackoverflow.com/questions/5007574/rendering-plaintext-as-html-maintaining-whitespace-without-pre/5047731#5047731">this suggestion</a> on this text:
<pre><code>First line\n Second line, indented four spaces\n Three spaces
<span class=grey>123456789•123456789•123456789•123456789•123456789•123456789•123456789•</span></code></pre>
<h3>Result</h3>
<p></p>
<div><code>
<script type="text/javascript">
var text = 'First line\n Second line, indented four spaces\n Three spaces';
var charEncodings = {
"\t": " ",
" ": " ",
"&": "&",
"<": "<",
">": ">",
"\n": "<br />",
"\r": "<br />"
};
var space = /[\t ]/;
var noWidthSpace = "​";
function textToHTML(text)
{
text = (text || "") + ""; // make sure it's a string;
text = text.replace(/\r\n/g, "\n"); // avoid adding two <br /> tags
var html = "";
var lastChar = "";
for (var i in text)
{
var char = text[i];
var charCode = text.charCodeAt(i);
if (space.test(char) && !space.test(lastChar) && space.test(text[i + 1] || ""))
{
html += noWidthSpace;
}
html += char in charEncodings ? charEncodings[char] :
charCode > 127 ? "&#" + charCode + ";" : char;
lastChar = char;
}
return html;
}
document.write(textToHTML(text));
</script><br /><span class=grey>123456789•123456789•123456789</span>
</div></code>
<h2></h2>
</body>
</html>