jQuery Page Widget How to - Shorten text with substring








Question

We would like to know how to shorten text with substring.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.4.4.min.js'></script>
<style type='text/css'>
.elem {<!--from  w w  w.  ja  va2  s .  com-->
  width: 150px;
  background: grey;
}
</style>
<script type='text/javascript'>
$(window).load(function(){
    $short = $('.short');
    $short.html($short.html().substring(0,10) + " ...");
});
</script>
</head>
<body>
  <div class="elem">
    <div class="short">Text should stay on one line</div>
    <div class="main">main</div>
  </div>
</body>
</html>

The code above is rendered as follows: