Last active
August 29, 2015 14:03
-
-
Save janbiasi/a173680e1a28e8600927 to your computer and use it in GitHub Desktop.
String excerption in JavaScript and C# for shortening messages or other strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Excerpt; | |
var message = Console.ReadLine(); // Hello my friend, how are you today? | |
Console.WriteLine(Excerpt(message, 20)); // Returns "Hello my friend, how..." |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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