using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI.WebControls;
namespace Extensions
{
public static class StringExtensions
{
///
/// Returns the given string truncated to the specified length, suffixed with an elipses (...)
///
///
/// Maximum length of return string
///
public static string Truncate(this string input, int length)
{
return Truncate(input, length, "...");
}
///
/// Returns the given string truncated to the specified length, suffixed with the given value
///
///
/// Maximum length of return string
/// The value to suffix the return value with (if truncation is performed)
///
public static string Truncate(this string input, int length, string suffix)
{
if (input == null) return "";
if (input.Length <= length) return input;
if (suffix == null) suffix = "...";
return input.Substring(0, length - suffix.Length) + suffix;
}
///
/// Splits a given string into an array based on character line breaks
///
///
/// String array, each containing one line
public static string[] ToLineArray(this string input)
{
if (input == null) return new string[] { };
return System.Text.RegularExpressions.Regex.Split(input, "\r\n");
}
///
/// Splits a given string into a strongly-typed list based on character line breaks
///
///
/// Strongly-typed string list, each containing one line
public static List ToLineList(this string input)
{
List output = new List();
output.AddRange(input.ToLineArray());
return output;
}
///
/// Replaces line breaks with self-closing HTML 'br' tags
///
///
///
public static string ReplaceBreaksWithBR(this string input)
{
return string.Join("
", input.ToLineArray());
}
///
/// Replaces any single apostrophes with two of the same
///
///
/// String
public static string DoubleApostrophes(this string input)
{
return Regex.Replace(input, "'", "''");
}
///
/// Encodes the input string as HTML (converts special characters to entities)
///
///
/// HTML-encoded string
public static string ToHTMLEncoded(this string input)
{
return HttpContext.Current.Server.HtmlEncode(input);
}
///
/// Encodes the input string as a URL (converts special characters to % codes)
///
///
/// URL-encoded string
public static string ToURLEncoded(this string input)
{
return HttpContext.Current.Server.UrlEncode(input);
}
///
/// Decodes any HTML entities in the input string
///
///
/// String
public static string FromHTMLEncoded(this string input)
{
return HttpContext.Current.Server.HtmlDecode(input);
}
///
/// Decodes any URL codes (% codes) in the input string
///
///
/// String
public static string FromURLEncoded(this string input)
{
return HttpContext.Current.Server.UrlDecode(input);
}
///
/// Removes any HTML tags from the input string
///
///
/// String
public static string StripHTML(this string input)
{
return Regex.Replace(input, @"<(style|script)[^<>]*>.*?\1>|?[a-z][a-z0-9]*[^<>]*>|", "");
}
}
}