[javascript] Display only 10 characters of a long string?

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.

This question is related to javascript jquery substring string-length

The answer is


('very long string'.slice(0,10))+'...'
// "very long ..."

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.


Try this :)

var mystring = "How do I get a long text string";
mystring = mystring.substring(0,10);
alert(mystring);

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..."


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);

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?


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));

@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'); 

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;
            }
         };

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.


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


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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to substring

Go test string contains substring How does String substring work in Swift Delete the last two characters of the String Split String by delimiter position using oracle SQL How do I check if a string contains another string in Swift? Python: Find a substring in a string and returning the index of the substring bash, extract string before a colon SQL SELECT everything after a certain character Finding second occurrence of a substring in a string in Java Select query to remove non-numeric characters

Examples related to string-length

String field value length in mongoDB SQL SELECT everything after a certain character Length of string in bash Get column value length, not column max length of value How to get the number of characters in a string How to find the length of a string in R Retrieve the maximum length of a VARCHAR column in SQL Server Measure string size in Bytes in php How to get the size of a string in Python? Display only 10 characters of a long string?