Truncate String When It Is Too Long

Smart way to truncate long strings

Essentially, you check the length of the given string. If it's longer than a given length n, clip it to length n (substr or slice) and add html entity (…) to the clipped string.

Such a method looks like

function truncate(str, n){
return (str.length > n) ? str.slice(0, n-1) + '…' : str;
};

If by 'more sophisticated' you mean truncating at the last word boundary of a string then you need an extra check.
First you clip the string to the desired length, next you clip the result of that to its last word boundary

function truncate( str, n, useWordBoundary ){
if (str.length <= n) { return str; }
const subString = str.slice(0, n-1); // the original check
return (useWordBoundary
? subString.slice(0, subString.lastIndexOf(" "))
: subString) + "…";
};

You can extend the native String prototype with your function. In that case the str parameter should be removed and str within the function should be replaced with this:

String.prototype.truncate = String.prototype.truncate || 
function ( n, useWordBoundary ){
if (this.length <= n) { return this; }
const subString = this.slice(0, n-1); // the original check
return (useWordBoundary
? subString.slice(0, subString.lastIndexOf(" "))
: subString) + "…";
};

More dogmatic developers may chide you strongly for that ("Don't modify objects you don't own". I wouldn't mind though).

An approach without extending the String prototype is to create
your own helper object, containing the (long) string you provide
and the beforementioned method to truncate it. That's what the snippet
below does.

const LongstringHelper = str => {
const sliceBoundary = str => str.substr(0, str.lastIndexOf(" "));
const truncate = (n, useWordBoundary) =>
str.length <= n ? str : `${ useWordBoundary
? sliceBoundary(str.slice(0, n - 1))
: str.slice(0, n - 1)}…`;
return { full: str, truncate };
};
const longStr = LongstringHelper(`Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum`);

const plain = document.querySelector("#resultTruncatedPlain");
const lastWord = document.querySelector("#resultTruncatedBoundary");
plain.innerHTML =
longStr.truncate(+plain.dataset.truncateat, !!+plain.dataset.onword);
lastWord.innerHTML =
longStr.truncate(+lastWord.dataset.truncateat, !!+lastWord.dataset.onword);
document.querySelector("#resultFull").innerHTML = longStr.full;
body {
font: normal 12px/15px verdana, arial;
}

p {
width: 450px;
}

#resultTruncatedPlain:before {
content: 'Truncated (plain) n='attr(data-truncateat)': ';
color: green;
}

#resultTruncatedBoundary:before {
content: 'Truncated (last whole word) n='attr(data-truncateat)': ';
color: green;
}

#resultFull:before {
content: 'Full: ';
color: green;
}
<p id="resultTruncatedPlain" data-truncateat="120" data-onword="0"></p>
<p id="resultTruncatedBoundary" data-truncateat="120" data-onword="1"></p>
<p id="resultFull"></p>

How can I truncate my strings with a ... if they are too long?

Here is the logic wrapped up in an extension method:

public static string Truncate(this string value, int maxChars)
{
return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "...";
}

Usage:

var s = "abcdefg";

Console.WriteLine(s.Truncate(3));

How can I truncate string values that are too long?

You can use pathinfo to separate the name from the extension. Then there are various ways to shorten and add the ellipsis. The method from this answer is very straightforward. You can map this method over your array to format all of the items.

$max = 11;

$formatted = array_map(function($file) use ($max) {
$info = pathinfo($file['name']);
$name = $info['filename'];
$name = strlen($name) > $max ? substr($name, 0, $max) . '...' : $name;
return "$name$info[extension] $file[size]";
}, $myarray);

Truncating a string to certain length, and then adding characters to the end in C

You are segfaulting because you didn't allocate memory to store where nCpy is pointing at.

char *nCpy = NULL; //the truncated name

Should be something like

char *nCpy = malloc(sizeof(char) * NAME_LENGTH + 1); //the truncated name

What you're trying now is to write to some junk value in memory, who knows, which almost always leads to a segmentation fault.

As Paul points out, you need to allocate space for NAME_LENGTH characters, plus one since a character string is null terminated with the special /0 character.
This specific error is called dereferencing a null pointer

Python truncate a long string

info = (data[:75] + '..') if len(data) > 75 else data

Truncate string in Rails: ... showing up on strings at length

truncate is the right method. This might be a bug in your version of rails? Here's what I get on my console:

[5] pry(main)> helper.truncate("This post is exactly 56 characters characters characters characte", length: 65)
=> "This post is exactly 56 characters characters characters characte"
[6] pry(main)> helper.truncate("This post is exactly 56 characters characters characters characte", length: 64)
=> "This post is exactly 56 characters characters characters char..."

I'm running Rails 4.0.4 in this example.



Related Topics



Leave a reply



Submit