Wednesday, June 30, 2010

HTML Encode Text in JavaScript

There are many ways of HTML encoding text in JavaScript. You may use string replacement using RegEx or simply hardcode replacements. These approaches help solve the purpose but make the code bloated and difficult to maintain. There is one clean way of achieving this.


function HTMLEncode(value){
var div = document.createElement(“DIV”);
var textNode = document.createTextNode(value);
div.appendChild(textNode);
return div.innerHTML;
}


The above code will html encode your text in a cleaner and faster way

Wrap long lines using CSS and JavaScript

I had this annoying problem of long unwrap-able lines breaking my website layout. After experimenting many fixes I finally settled on the following fix.


<script type="text/javascript">
$(function(){
$(".wrap").each(function(){
$(this).html(
$(this)
.text()
.replace(/([^\s-]{5})/g, "$&&shy;")
);
});
});
</script>



The above code uses jQuery and Regular Expression to wrap text in tags which have the class "wrap" by adding &shy; after every 5 characters in a long word. For more information on &shy; refer the references section below.

References: