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

Display only 10 characters of a long string?


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


var example = "I am too long string";var result;// Slice is JS functionresult = example.slice(0, 10)+'...'; //if you need dots after the string you can add

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