How to crop a string exceeding the length of an element?

On my html page I have a hint. Some lines are incorrectly set due to their length in the tooltip image. But I am not allowed to trim the string from the server side.

I want the tooltip to display the first 8-12 characters and then the dots.

Is there a built-in function for javascript or jquery.

Thank!

+3
source share
6 answers

You can use string.substring(from, to): http://www.w3schools.com/jsref/jsref_substring.asp

Then just add "..."

var x = "a really long line of text";
var toolTipText = x.substring(0, 8) + "...";
+9
source
tip = tip.length > 12 ? tip.substring(0,12) + "..." : tip;
+10
source

, , :

var regExp = /(.{8})(.*)/;
<YOUR_INPUT_STRING>.replace(regExp, "$1...");
 //e.g. "It is a very big string I donno why it is so big.".replace(regExp, "$1...");
+2

(, CSS3 text-overflow: ) , , , , . Javascript #. , . :

String # replace , .

, 8 , , :

function replace_second_group_with_an_ellipsis(){
    return arguments[1] + (arguments[2] ? '...' : '');
}

toolTipString.replace(/(^.{0,8})(.*)/, replace_second_group_with_an_ellipsis);

, replace(), arguments , .

, , . , . , javascript . :

function shorten_nicely_with_ellipsis(){
    var str = arguments[1];
    var truncating = !!arguments[2];

    // If we're not already breaking on a whitespace character, loop
    // backwards over the string, and break on the first character of
    // the first group of whitespace characters we find. 
    if( truncating && !arguments[2].match(/^\s/) ) {
        for(var i=str.length; --i; i<=1) {
            if( str[i].match(/\s/) && !str[i-1].match(/\s/) ) {
                str = arguments[1].substr(0, i);
                break;
            }
        }
    }

    if( truncating ) {                
        str = str + '...';
    }

    return str;
}


toolTipString.replace(/(^.{0,8})(.*)/, shorten_nicely_with_ellipsis);
+2

Not really JavaScript (and not universal), but CSS text-overflow: ellipsiswill do what you want.

+1
source

CSS3 presents text-overflow: ellipsisexactly what you are looking for. Here 's an article about this, including how to make it work in firefox, which does not yet support the property.

0
source

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


All Articles