2011-01-15 4 views
18

szukam prostego skryptu, który można obciąć ciąg z wielokropkiem (...)Chcę obciąć tekst lub wiersz z wielokropkiem użyciu JavaScript

Chcę obciąć coś podobnego 'this is a very long string' do 'this is a ve...'

Nie chcę używać CSS ani PHP.

+3

Czy chcesz skrócić coś w stylu "to jest bardzo długi ciąg" na "to jest ve ..." itp.? –

+0

Czy możesz podać i przykład? A co masz na myśli przez TEKST? – jzd

+0

@El Ronnoco dokładnie! –

Odpowiedz

4

Coś jak:

var line = "foo bar lol"; 
line.substring(0, 5) + '...' // gives "foo b..." 
+3

To nie jest kompletne rozwiązanie. Musisz sprawdzić, czy łańcuch jest faktycznie większy niż kwota, którą zamierzasz obciąć. Jeśli false, to '...' nie powinno się pojawić. Samo użycie 'line.substring (0, max_char)' nie będzie wystarczającym rozwiązaniem. – user1952811

1

HTML z JavaScript:

<p id="myid">My long long looooong text cut cut cut cut cut</p> 

<script type="text/javascript"> 
var myid=document.getElementById('myid'); 
myid.innerHTML=myid.innerHTML.substring(0,10)+'...'; 
</script> 

Rezultatem będzie:

My long lo... 

Cheers

G.

46
function truncate(string){ 
    if (string.length > 5) 
     return string.substring(0,5)+'...'; 
    else 
     return string; 
}; 
+0

Ten (string.substr (0,5) + "...";) pracował dla mnie. –

1

Jeśli chcesz wyciąć ciąg o długości specifited i dodać kropki używać

// Length to cut 
var lengthToCut = 20; 

// Sample text 
var text = "The quick brown fox jumps over the lazy dog"; 

// We are getting 50 letters (0-50) from sample text 
var cutted = text.substr(0, lengthToCut); 
document.write(cutted+"..."); 

Lub jeśli chcesz nie cięte według długości, ale ze słowami liczyć zastosowanie:

// Number of words to cut 
var wordsToCut = 3; 

// Sample text 
var text = "The quick brown fox jumps over the lazy dog"; 

// We are splitting sample text in array of words 
var wordsArray = text.split(" "); 

// This will keep our generated text 
var cutted = ""; 
for(i = 0; i < wordsToCut; i++) 
cutted += wordsArray[i] + " "; // Add to cutted word with space 

document.write(cutted+"..."); 

Powodzenia ...

2
function truncate(string, length, delimiter) { 
    delimiter = delimiter || "&hellip;"; 
    return string.length > length ? string.substr(0, length) + delimiter : string; 
}; 

var long = "Very long text here and here", 
    short = "Short"; 

truncate(long, 10); // -> "Very long ..." 
truncate(long, 10, ">>"); // -> "Very long >>" 
truncate(short, 10); // -> "Short" 
19

KooiInc ma na to dobrą odpowiedź. Podsumowując:

String.prototype.trunc = 
     function(n){ 
      return this.substr(0,n-1)+(this.length>n?'&hellip;':''); 
     }; 

Teraz można zrobić:

var s = 'not very long'; 
s.trunc(25); //=> not very long 
s.trunc(5); //=> not... 

Pełna zasługa KooiInc do tego.

+1

Zwięzłe jest ładne. Użyłem go jako: 'function truncateWithEllipses (text, max) {return text.substr (0, max-1) + (text.length> max? '& Hellip;': ''); } ' –

1

To będzie umieścić wielokropka w środku linii:

function truncate(str, max, sep) { 

    // Default to 10 characters 
    max = max || 10; 

    var len = str.length; 
    if(len > max){ 

     // Default to elipsis 
     sep = sep || "..."; 

     var seplen = sep.length; 

     // If seperator is larger than character limit, 
     // well then we don't want to just show the seperator, 
     // so just show right hand side of the string. 
     if(seplen > max) { 
      return str.substr(len - max); 
     } 

     // Half the difference between max and string length. 
     // Multiply negative because small minus big. 
     // Must account for length of separator too. 
     var n = -0.5 * (max - len - seplen); 

     // This gives us the centerline. 
     var center = len/2; 

     var front = str.substr(0, center - n); 
     var back = str.substr(len - center + n); // without second arg, will automatically go to end of line. 

     return front + sep + back; 

    } 

    return str; 
} 

console.log(truncate("123456789abcde")); // 123...bcde (using built-in defaults) 
console.log(truncate("123456789abcde", 8)); // 12...cde (max of 8 characters) 
console.log(truncate("123456789abcde", 12, "_")); // 12345_9abcde (customize the separator) 

Na przykład:

1234567890 --> 1234...8910 

oraz:

A really long string --> A real...string 

Nie idealne, ale funkcjonalny. Wybacz, że komentujesz ... dla noobów.

+0

Niektóre inne podobne funkcje: http://stackoverflow.com/questions/831552/ellipsis-in-middle-of-a-text-mac-style/30613599#30613599 – bob

5

Najprostsza i elastyczny sposób: JSnippet DEMO

styl Funkcja:

function truncString(str, max, add){ 
    add = add || '...'; 
    return (typeof str === 'string' && str.length > max ? str.substring(0,max)+add : str); 
}; 

Prototype:

String.prototype.truncString = function(max, add){ 
    add = add || '...'; 
    return (this.length > max ? this.substring(0,max)+add : this); 
}; 

Zastosowanie:

str = "testing with some string see console output"; 

//By prototype: 
console.log( str.truncString(15,'...') ); 

//By function call: 
console.log( truncString(str,15,'...') ); 
1

Spróbuj

function shorten(text, maxLength, delimiter, overflow) { 
    delimiter = delimiter || "&hellip;"; 
    overflow = overflow || false; 
    var ret = text; 
    if (ret.length > maxLength) { 
    var breakpoint = overflow ? maxLength + ret.substr(maxLength).indexOf(" ") : ret.substr(0, maxLength).lastIndexOf(" "); 
    ret = ret.substr(0, breakpoint) + delimiter; 
    } 
    return ret; 
} 

$(document).ready(function() { 
    var $editedText = $("#edited_text"); 
    var text = $editedText.text(); 
    $editedText.text(shorten(text, 33, "...", false)); 
}); 

Zamówienie próbki roboczej na Codepen http://codepen.io/Izaias/pen/QbBwwE

0

Pozwoli to ograniczyć je do jednak wiele linii chcesz to ograniczone do i reaguje

Pomysł, że nikt nie zasugerował, robi w oparciu o wysokość elementu, a następnie usuwając go stamtąd.

Fiddle - https://jsfiddle.net/hutber/u5mtLznf/ < - wersja ES6

Ale w zasadzie chcesz chwycić wysokość wiersza elementu, pętlę przez cały tekst i zatrzymać, gdy jej na wysokości pewne linie:

'use strict'; 

var linesElement = 3; //it will truncate at 3 lines. 
var truncateElement = document.getElementById('truncateme'); 
var truncateText = truncateElement.textContent; 

var getLineHeight = function getLineHeight(element) { 
    var lineHeight = window.getComputedStyle(truncateElement)['line-height']; 
    if (lineHeight === 'normal') { 
    // sucky chrome 
    return 1.16 * parseFloat(window.getComputedStyle(truncateElement)['font-size']); 
    } else { 
    return parseFloat(lineHeight); 
    } 
}; 

linesElement.addEventListener('change', function() { 
    truncateElement.innerHTML = truncateText; 
    var truncateTextParts = truncateText.split(' '); 
    var lineHeight = getLineHeight(truncateElement); 
    var lines = parseInt(linesElement.value); 

    while (lines * lineHeight < truncateElement.clientHeight) { 
    console.log(truncateTextParts.length, lines * lineHeight, truncateElement.clientHeight); 
    truncateTextParts.pop(); 
    truncateElement.innerHTML = truncateTextParts.join(' ') + '...'; 
    } 
}); 

CSS

#truncateme { 
    width: auto; This will be completely dynamic to the height of the element, its just restricted by how many lines you want it to clip to 
} 
1

Dla zapobiegania kropki w środku wyrazu lub AF ter symbol interpunkcji.

let parseText = function(text, limit){ 
if (text.length > limit) 
    for (let i = limit; i > 0; i--){ 
     if(text.charAt(i) === ' ' && (text.charAt(i-1) != ','||text.charAt(i-1) != '.'||text.charAt(i-1) != ';')) { 
      return text.substring(0, i) + '...'; 
     } 
    } 
else 
    return text; 
}; 
Powiązane problemy