Carlos Carlos - 6 months ago 30
jQuery Question

Set text limit using jquery

There is some text comprised of 165 characters. I need to show only the first 155 characters, but the last 5 out of the 155 chars should be replaced with "....." (elipses), and the remaining characters should be removed. fiddle

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
var txt= $('div').text();
for(i=0;i<2;i++){
alert(txt.charAt(150+ i))
}
})
</script>
</head>
<body>
<div style="width:100px">
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that
</div>
</body>

Answer Source

Check out the substring function here, and voilà:

var txt= $('#restrict').text();
if(txt.length > 155)
    $('#result').text(txt.substring(0,150) + '.....');

http://jsfiddle.net/techunter/GRmY2/