Set text limit with jquery

There is a text consisting of 165 characters. I need to show only the first 155 characters, but the last 5 of 155 characters should be replaced with "....." (elipses), and the rest of the characters should be deleted. 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> 
+4
source share
4 answers

Check the substring here , and voilร :

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

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

+8
source

Depending on which browsers you are targeting, you can simply use css.

 text-overflow: ellipsis 
+5
source

It seems that TecHunter has already published almost the same thing, but I was bored and did it.

In 155 characters, instead of 5 characters, "...." is replaced. It has an input to textarea with a character counter, which is updated as you type.

Html

 <div> <h2>Input</h2> <textarea id="sampleInput"> 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 </textarea> </div> <div> <label>Character Count:</label> <span id ="charCounter"></span> <div> <h2>Output</h2> <p style="width:100px" id="sampleOutput"></p> 

Js

 updateOutput(); $('#sampleInput').keyup(function(e){ updateOutput(); }); function updateOutput(){ var sampleInput = $('#sampleInput').val(), sampleInputLength = sampleInput.length; if(sampleInputLength >= 155) { sampleInput = sampleInput.substr(0,150) + "....."; } $('#charCounter').text(sampleInputLength); $('#sampleOutput').text(sampleInput); } 

CSS

 #sampleInput { width: 400px; height:100px; } 

jsfiddle

+2
source

I saw some good answers, by the way, some of them are ineffective in other cases, for example: when you copy and paste something. So, I would suggest:

  $(document).on('keyup keypress blur change', '#elementId', function () { var maxLength = 100; // number of characters to limit imposeMaxLength($(this), maxLength); }); function imposeMaxLength(element, maxLength) { if (element.val().length > maxLength) { element.val(element.val().substring(0, maxLength)); } } 

Using the imposeMaxLength function as a function, you can reuse it in other events.

0
source

Source: https://habr.com/ru/post/1483615/


All Articles