JavaScript function to truncate string to given length and appending truncate string. In this function default truncate string is “…”. This function is safe all conditions are handled.
Here is function with example.
<script type="text/javascript"> function makeString(object) { if (object == null) return \'\'; return String(object); }; function truncate(str, length, truncateStr) { str = makeString(str); truncateStr = truncateStr || \'...\'; length = ~~length; return str.length > length ? str.slice(0, length) + truncateStr : str; }; //test function alert(truncate(\'hello world\',14)); </script>
Here is output