117

How do I get a long text string (like a querystring) to display a maximum of 10 characters, using JQuery?

Sorry guys I'm a novice at JavaScript & JQuery :S
Any help would be greatly appreciated.

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
Nasir
  • 4,785
  • 10
  • 35
  • 39
  • Can you clarify with an example? – Andy E Aug 05 '10 at 13:09
  • Is it jquery because it's a string in a DOM element? – sje397 Aug 05 '10 at 13:09
  • 1
    @Gopi yes I mean ellipsize To clarify...I am working on a intranet system where users are able to raise cases...some users add a super long querystring that breaks a table layout when displayed on the homepage. I want to intercept this querystring by checking(using JQuery) for anything that is 10 characters plus without spaces and ellipsize it (e.g. this=is-a-really-long&string... ) Please let me know if this makes sense. Thanks – Nasir Aug 05 '10 at 13:22
  • 1
    It worked at [here](https://stackoverflow.com/a/46049705/6537098) Good Sucess! – Tran Anh Hien Sep 05 '17 at 08:02
  • browsers can automatically add ellipsis to strings that would break the bounds of an element (see my answer below) – Alnitak Dec 03 '18 at 12:13

14 Answers14

216

If I understand correctly you want to limit a string to 10 characters?

var str = 'Some very long string';
if(str.length > 10) str = str.substring(0,10);

Something like that?

Sebs
  • 2,978
  • 1
  • 15
  • 10
  • 21
    The *if* statement is optional here. *str.substring(0,10)* on a string with less than 10 characters would remain unaffected :) – Andy E Aug 05 '10 at 13:11
  • 12
    but the if statement can be used to something like: { var str = 'Some very long string'; if(str.length > 10) str = str.substring(0,10)+"..."; } – Daniel Wedlund Aug 05 '10 at 13:13
  • @Daniel: true, it would be necessary for adding an ellipsis. Luckily I used the word *optional* :-) – Andy E Aug 05 '10 at 13:15
  • 4
    @Daniel, "if(str.length > 10) str = str.substring(0,10)+"..."; }" is wrong because the resultstring has a length of 13 not 10 !! correct: "if(str.length > 10) str = str.substring(0,10-3)+"..."; }" – Floyd Aug 05 '10 at 13:42
  • 1
    [Here's a performance test](http://jsperf.com/cap-string-to-length/2) for those who care. They perform almost the same if the case where substring is actually needed happens 50% of the time. – Ruan Mendes Nov 12 '15 at 16:03
36
var example = "I am too long string";
var result;

// Slice is JS function
result = example.slice(0, 10)+'...'; //if you need dots after the string you can add

Result variable contains "I am too l..."

JJJ
  • 32,902
  • 20
  • 89
  • 102
Ranjita Naik
  • 361
  • 3
  • 4
35

Creating own answer, as nobody has considered that the split might not happened (shorter text). In that case we don't want to add '...' as suffix.

Ternary operator will sort that out:

var text = "blahalhahkanhklanlkanhlanlanhak";
var count = 35;

var result = text.slice(0, count) + (text.length > count ? "..." : "");

Can be closed to function:

function fn(text, count){
    return text.slice(0, count) + (text.length > count ? "..." : "");
}

console.log(fn("aognaglkanglnagln", 10));

And expand to helpers class so You can even choose if You want the dots or not:

function fn(text, count, insertDots){
    return text.slice(0, count) + (((text.length > count) && insertDots) ? "..." : "");
}

console.log(fn("aognaglkanglnagln", 10, true));
console.log(fn("aognaglkanglnagln", 10, false));
Tatranskymedved
  • 4,194
  • 3
  • 21
  • 47
22

And here's a jQuery example:

HTML text field:

<input type="text" id="myTextfield" />

jQuery code to limit its size:

var elem = $("#myTextfield");
if(elem) elem.val(elem.val().substr(0,10));

As an example, you could use the jQuery code above to restrict the user from entering more than 10 characters while he's typing; the following code snippet does exactly this:

$(document).ready(function() {
    var elem = $("#myTextfield");
    if (elem) {
        elem.keydown(function() {
            if (elem.val().length > 10)
                elem.val(elem.val().substr(0, 10));
        });
    }            
});

Update: The above code snippet was only used to show an example usage.

The following code snippet will handle you issue with the DIV element:

$(document).ready(function() {
    var elem = $(".tasks-overflow");
    if(elem){
        if (elem.text().length > 10)
                elem.text(elem.text().substr(0,10))
    }
});

Please note that I'm using text instead of val in this case, since the val method doesn't seem to work with the DIV element.

Giuseppe Accaputo
  • 2,642
  • 17
  • 23
  • Hi Giu, I am not dealing with the text when it is being input...rather when it gets displayed and break my table layout. The querystring text is displayed in a DIV called .tasks-overflow – Nasir Aug 05 '10 at 13:31
  • @Nasir Thanks for the hint; I've updated my answer; it should help you solve your little issue – Giuseppe Accaputo Aug 05 '10 at 13:40
  • Hi Giu, I've tried your code and it hasn't worked. I want this long string 'thisisonelooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooongquerystring' to display as 'thisisonelooo...' – Nasir Aug 05 '10 at 13:41
  • This is how the code looks: $(document).ready(function(){ $(".tasks-overflow:contains('http://')").each(function(){ var self = $(this) , txt = self.text(); txt = txt.replace(/(http[s]*:[\/\\]{2})[^\s]*/g,'$1...'); self.text(txt); }); //Giu code var elem = $(".tasks-overflow"); if(elem){ if (elem.val().length > 10) elem.val(elem.val().substr(0,10)) } }); – Nasir Aug 05 '10 at 13:42
  • @Nasir I'm sorry; my old answer contained the `val` method, which doesn't seem to work for DIV elements. I've updated my answer again, and now the `text` method is used to alter the text, which should work perfectly (tested it locally, again). Could you please test it again with my updated code and let me know? – Giuseppe Accaputo Aug 05 '10 at 13:49
  • @Giu - It is working although the code is taking out all text in that DIV...I need it to target only long querystring(10 characters & over)...not short words or spaces inbetween words. Thanks – Nasir Aug 05 '10 at 13:54
  • @Nasir You could use the following RegExp to filter out / replace your string, assuming that it only consists of letters: `/[a-zA-Z]{10}/` – Giuseppe Accaputo Aug 05 '10 at 14:11
  • @Giu how would I go about implementing a RegExp? – Nasir Aug 05 '10 at 15:54
13
('very long string'.slice(0,10))+'...'
// "very long ..."
Kai Light
  • 164
  • 2
  • 11
5

html

<p id='longText'>Some very very very very very very very very very very very long string</p>

javascript (on doc ready)

var longText = $('#longText');
longText.text(longText.text().substr(0, 10));

If you have multiple words in the text, and want each to be limited to at most 10 chars, you could do:

var longText = $('#longText');
var text = longText.text();
var regex = /\w{11}\w*/, match;
while(match = regex.exec(text)) {
    text = text.replace(match[0], match[0].substr(0, 10));
}
longText.text(text);
sje397
  • 41,293
  • 8
  • 87
  • 103
  • 2
    *.text()* is more appropriate than *.html()* when dealing with text only. – Andy E Aug 05 '10 at 13:13
  • Hi sje397, I need to be able to ignore other words before & after this string (this string is a long querystring & has no spaces) thanks – Nasir Aug 05 '10 at 13:26
  • @Nasir - you can change the arguments to substr...or you might want to look at regular expressions. – sje397 Aug 05 '10 at 13:39
4

What you should also do when you truncate the string to ten characters is add the actual html ellipses entity: &hellip;, rather than three periods.

Ken Ray
  • 2,500
  • 3
  • 21
  • 28
4

Although this won't limit the string to exactly 10 characters, why not let the browser do the work for you with CSS:

.no-overflow {
    white-space: no-wrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

and then for the table cell that contains the string add the above class and set the maximum permitted width. The result should end up looking better than anything done based on measuring the string length.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
4
A = "a lennnnnnnnnnnnngthy string ";

word = A.substring(0, number_of_words_to_appear) + "...";

console.log(word)
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Syed anas
  • 41
  • 1
3

This looks more to me like what you probably want.

$(document).ready(function(){
var stringWithShorterURLs = getReplacementString($(".tasks-overflow").text());

function getReplacementString(str){
    return str.replace(/(https?\:\/\/[^\s]*)/gi,function(match){
        return match.substring(0,10) + "..."
    });
}});


you give it your html element in the first line and then it takes the whole text, replaces urls with 10 character long versions and returns it to you. This seems a little strange to only have 3 of the url characters so I would recommend this if possible.

$(document).ready(function(){
var stringWithShorterURLs = getReplacementString($(".tasks-overflow p").text());

function getReplacementString(str){
    return str.replace(/https?\:\/\/([^\s]*)/gi,function(match){
        return match.substring(0,10) + "..."
    });
}});

which would rip out the http:// or https:// and print up to 10 charaters of www.example.com

mraaroncruz
  • 3,780
  • 2
  • 32
  • 31
3

Try this :)

var mystring = "How do I get a long text string";
mystring = mystring.substring(0,10);
alert(mystring);
Vishal P Gothi
  • 987
  • 5
  • 15
1

@jolly.exe

Nice example Jolly. I updated your version which limits the character length as opposed to the number of words. I also added setting the title to the real original innerHTML , so users can hover and see what is truncated.

HTML

<div id="stuff">a reallly really really long titleasdfasdfasdfasdfasdfasdfasdfadsf</div> 

JS

 function cutString(id){    
     var text = document.getElementById(id).innerHTML;         
     var charsToCutTo = 30;
        if(text.length>charsToCutTo){
            var strShort = "";
            for(i = 0; i < charsToCutTo; i++){
                strShort += text[i];
            }
            document.getElementById(id).title = "text";
            document.getElementById(id).innerHTML = strShort + "...";
        }            
     };

cutString('stuff'); 
DaFrenzy
  • 121
  • 6
1
const text = 'imathelongtextblablabla'
const showLess = false
{!showLess && `${text.substring(0, 10)}`}
{!showLess && "..."}
DINA TAKLIT
  • 7,074
  • 10
  • 69
  • 74
T.C
  • 11
  • 1
-2

Show this "long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text "

to

long text long text long ...

        function cutString(text){    
            var wordsToCut = 5;
            var wordsArray = text.split(" ");
            if(wordsArray.length>wordsToCut){
                var strShort = "";
                for(i = 0; i < wordsToCut; i++){
                    strShort += wordsArray[i] + " ";
                }   
                return strShort+"...";
            }else{
                return text;
            }
         };
Code Spy
  • 9,626
  • 4
  • 66
  • 46