Skip to content

Instantly share code, notes, and snippets.

@janbiasi
Last active August 29, 2015 14:03
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save janbiasi/a173680e1a28e8600927 to your computer and use it in GitHub Desktop.
String excerption in JavaScript and C# for shortening messages or other strings
/// <summary>
/// Create excerpt string with n characters
/// </summary>
/// <param name="longString">The long string</param>
/// <param name="delimiter">How many chars there should be</param>
/// <returns>Shortened string</returns>
public static string Excerpt(string longString, int delimiter = 30) {
string shortened = ""; int i = 0;
if (String.IsNullOrEmpty(longString) == false) {
if (longString.Length > delimiter) {
foreach (var c in longLink) {
if (i < delimiter) shortened += c;
if (i == delimiter) shortened += "...";
i++;
}
} else {
return longString;
}
}
return shortened;
}
/**
* Excerpts a string with <delimiter> chars
* @param {int} delimiter How many chars'd be cutted
* @return {string} Excerpted or full string
*/
String.prototype.excerpt = function (delimiter) {
delimiter = delimiter || 30;
if (this.length > delimiter) {
var cutted = [], i = 0;
delimiter = delimiter == 'undefined' || delimiter == null ? 25 : delimiter;
while (i < delimiter) {
cutted.push(this[i]);
i++;
}
return cutted.join("") + "...";
} else {
return this;
}
};
using Excerpt;
var message = Console.ReadLine(); // Hello my friend, how are you today?
Console.WriteLine(Excerpt(message, 20)); // Returns "Hello my friend, how..."
var message = "Hello my friend, how are you today?";
alert(message.excerpt(20)); // Returns "Hello my friend, how..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment