Monday, December 14, 2009

WrapText function in javascript.

Some times in highly user interactive sites like forums and community domain. User may enter continues text as long word and which will not be warped automatically.
To wrap text it needs White spaces between words, if it can't find space it will distort our design and looks of page will not remain as it is. to handle such condition we can split long word after specified characters.
we can do this server side or client side. i have written a function in Javascript.Called WrapText.
Regular expression is the best way to do this task with effective and minimal code.
you can use this as per you need ,or using same Regular expression you can write function in C# or VB.
here is the function in javascript.
<script type="text/javascript" language="javascript">
function WrapText(Input) {
var FillChar = "</br>";
var MaxLength = 10;
var pattern = new RegExp("([^\\s-]
{" + MaxLength + "})", "g");
var myString = Input;
return myString.replace(pattern, "$1"+FillChar);
}
alert(WrapText('HI_JAVSCRIPT_HOW_YOU_DOING'));
</script>

Thanks,