Hello, I wrote a simple script in javascript to convert plain text to html, any suggestions, advice… etc., would be greatly appreciated. I’m showing here the full source code for the 3 files: html, css, and javascript:
First, the html code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>converter_v2</title>
<link href="css/styles.css" type="text/css" rel="stylesheet" />
</head>
<body>
<form>
<p>Input Text Here</p>
<p><textarea id="in_txt"></textarea></p>
<p>Press Convert Below to Start Converting!</p>
<p><textarea id="out_html"></textarea></p>
</form>
<button id="btn">Convert!</button>
<script src="js/converter.js"></script>
</body>
</html>
The javascript code:
function convert() {
var input_str; //store input
var text_input; //store input after beging trim()med
var output_html=""; //store output
var counter;
input_str=document.getElementById('in_txt').value; //get input and store it in input_str
text_input=input_str.trim(); //trim() input
if(text_input.length > 0){
output_html+="<p>"; //begin by creating paragraph
for(counter=0; counter < text_input.length; counter++){
switch (text_input[counter]){
case '\n':
if (text_input[counter+1]==='\n'){
output_html+="</p>\n<p>";
counter++;
}
else output_html+="<br>";
break;
case ' ':
if(text_input[counter-1] != ' ' && text_input[counter-1] != '\t')
output_html+=" ";
break;
case '\t':
if(text_input[counter-1] != '\t')
output_html+=" ";
break;
case '&':
output_html+="&";
break;
case '"':
output_html+=""";
break;
case '>':
output_html+=">";
break;
case '<':
output_html+="<";
break;
default:
output_html+=text_input[counter];
}
}
output_html+="</p>"; //finally close paragraph
}
document.getElementById('out_html').value = output_html; // display output html
}
var el = document.getElementById('btn');
el.onclick = convert;
the css code:
textarea {
width: 45%;
height: 200px;
}
I would like to mention here a little rule I’m following: if the script comes across 2 consecutive new lines in the input, it will begin a new paragraph in the output, if it comes across one new line, it will output a <br>.
Thank you.