Some sites that offer tutorials would want to display HTML (or other similar codes such as XML and JavasScript) on their sites. But since these are also codes for the web, browsers will interpret it as a part of the site's code rather than as texts.

In order for you to display this as is, you may want to clean your codes first into an browser friendly text by converting some characters to its HTML code equivalent.

The Online HTML Converter

Raw Code
 
Clean Code

The Logic Behind

What we are trying to do is convert all < and > signs into its HTML equivalent. Reason is, browsers treat this as tags and everything inside of < as parameters or attributes of the tag. We will convert & signs too for other languages such as JavaScript codes.
HTML
This code are just plain textareas (one for the raw and one for the processed) and two buttons for converting and reverting the process
<textarea class="codeInput" id="codeInput" cols="50" rows="10"></textarea>
<br/>
<textarea class="codeOutput" id="codeOutput" cols="50" rows="10" /></textarea>
<br/>
<input type="button" id="codeConvert" value="Convert" />
<input type="button" id="codeRevert" value="Revert" />
JQuery
I'll be using JQuery in here instead of plain JavaScript. Logic might be the same though.
$("#codeConvert").click(function () {
    $codeInput = $("#codeInput").val();
    $codeOutput = $codeInput.replace(/\&/g, "&#38;").replace(/\>/g, "&#62;").replace(/\</g, "&#60;");
    $("#codeOutput").val($codeOutput);
});

$("#codeRevert").click(function () {
    $codeOutput = $("#codeOutput").val();
    $codeInput = $codeOutput.replace(/\&#62;/g, ">").replace(/\&#60;/g, "<").replace(/\&#38;/g, "&");
    $("#codeInput").val($codeInput);
});

1 comment :