‟Let's talk about ex-tension methods, baby!”
Extension methods are a powerful feature of C# that allows developers to add new methods to existing types without the need for inheritance, modification or recompilation of the original class. Fortunately, the .Net family of frameworks provides numerous built-in extension methods, but with Umbraco you get an additional set of methods that can help you keep your code concise, readable, and aligned with the DRY principle.
By chance, I stumbled upon this collection of extensions a while back when intellisense suggested IsNullOrWhiteSpace()
and StripHtml()
to me. Knowing that these were not part of the vanilla .Net, I hit F12 (go to definition) and discovered a treasure trove of other extension methods. In this article, we will explore the plethora of string extension methods that Umbraco CMS offers and how to utilise them.
Please note that the information below pertains to Umbraco version 11.0, although some features may also be relevant to older and newer versions. These methods are found in the StringExtensions
class within the Umbraco.Extensions
namespace.
Table of contents
⭐ = My Favourite
- GetIdsFromPathReversed() - Returns the IDs of the items in a path in reverse order.
- StripWhitespace() - Removes whitespace characters from the beginning and end of a string.
- StripFileExtension() - Removes the file extension from a file path.
- GetFileExtension() - Returns the file extension of a file path.
- DetectIsJson() - Determines if a string is a valid JSON object.
- DetectIsEmptyJson() - Determines if a string is an empty JSON object.
- ⭐ReplaceNonAlphanumericChars() - Replaces all non-alphanumeric characters in a string with a specified replacement.
- CleanForXss() - Sanitizes a string to remove potential cross-site scripting (XSS) vulnerabilities.
- ExceptChars() - Returns a string with all instances of specified characters removed.
- GenerateStreamFromString() - Creates a stream from a string.
- ⭐AppendQueryStringToUrl() - Appends a query string to a URL.
- MakePluralName() - Returns the plural form of a noun.
- IsVowel() - Determines if a character is a vowel.
- Trim() - Removes whitespace characters from the beginning and end of a string.
- EncodeJsString() - Encodes a string to be used in a JavaScript string literal.
- EnsureStartsWith() - Ensures that a string starts with a specified prefix.
- EnsureEndsWith() - Ensures that a string ends with a specified suffix.
- IsLowerCase() - Determines if a string is all lowercase.
- IsUpperCase() - Determines if a string is all uppercase.
- ⭐IsNullOrWhiteSpace() - Determines if a string is null or consists only of whitespace characters.
- IfNullOrWhiteSpace() - Returns a default value if a string is null or consists only of whitespace characters.
- ⭐ToDelimitedList() - Converts a list of strings to a delimited string.
- EnumTryParse() - Provides a safer way to parse a string value to a specified enum type.
- EnumParse() - Provides an easy way to parse a string value to a specified enum type.
- ⭐StripHtml() - Removes HTML tags from a string.
- EncodeAsGuid() - Encodes a GUID as a string.
- ConvertToHex() - Converts a byte array to a hexadecimal string.
- DecodeFromHex() - Converts a hexadecimal string to a byte array.
- ToUrlBase64() - Converts a byte array to a URL-safe base64-encoded string.
- FromUrlBase64() - Decodes a URL-safe Base64 string into its original string representation.
- InvariantFormat() - Formats a string with invariant culture.
- ToInvariantString() - Converts an integer or long value to its invariant string representation.
- ⭐InvariantEquals() - Compares two strings in a case-insensitive manner and with invariant culture.
- ⭐InvariantStartsWith() - Checks if a string starts with a specific substring in a case-insensitive manner using the InvariantCultureIgnoreCase option.
- InvariantEndsWith() - Checks if a string ends with a specific substring in a case-insensitive manner using the InvariantCultureIgnoreCase option.
- ⭐InvariantContains() - Checks if a string or IEnumerable of strings contains a specific substring in a case-insensitive manner.
- ⭐InvariantIndexOf() - Finds the index of the first occurrence of a specific substring in a string in a case-insensitive manner using the OrdinalIgnoreCase option.
- InvariantLastIndexOf() - Finds the index of the last occurrence of a specific substring in a string in a case-insensitive manner using the OrdinalIgnoreCase option.
- ParseInto() - Attempts to parse a string into the supplied type by finding and using the Type's "Parse" method.
- GenerateHash() - Generates a hash of a string using a specified hash algorithm.
- ToSHA1() - Converts a string to its SHA1 hash value.
- UrlTokenDecode() - Decodes a string that was encoded with UrlTokenEncode.
- UrlTokenEncode() - Encodes a byte array for use in URLs, files, or other places where a string is required.
- NormaliseDirectoryPath() - Ensures a given directory path ends with a directory separator character.
- ⭐Truncate() - Truncates a given string to a specified length and appends a suffix at the end of it.
- StripNewLines() - Removes carriage returns and line feeds from a given string.
- ToSingleLine() - Converts a multiline string to a single line by replacing line breaks with spaces.
- OrIfNullOrWhiteSpace() - Returns the input string if it is not null or whitespace, otherwise, it returns the alternative string.
- ToFirstUpper() - Converts the first character of a string to uppercase.
- ToFirstLower() - Converts the first character of a string to lowercase.
-
ToFirstUpperInvariant() / ToFirstLowerInvariant() - Similar to
ToFirstUpper()
andToFirstLower()
, respectively, but they use the casing rules of the invariant culture. - ReplaceMany() - Replaces multiple occurrences of a set of characters or strings in a given string with a specified replacement character or string.
- ReplaceFirst() - A method that returns a new string in which only the first occurrence of a specified string is replaced by a specified replacement string.
- Replace() - A method that returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
- ToCSharpString() - A method that converts a literal string into a C# expression.
- EscapeRegexSpecialCharacters() - A method that escapes all the special characters used in a regular expression.
- ContainsAny() - A method that returns a boolean if any of the strings in the list of strings exists within the source string.
- CsvContains() - Checks if a comma-separated string (CSV) contains a given value.
- ⭐ToFriendlyName() - Converts a file name to a user-friendly name for a content item.
- ToValidXmlString() - Replaces all invalid Unicode characters in a string for XML files.
- ToGuid() - Converts a string to a GUID (Globally Unique Identifier).
- NullOrWhiteSpaceAsNull() - Turns a null-or-whitespace string into a null string.
- IsFullPath() - Checks whether a given path is a full path including drive letter.
- ⭐ToSafeAlias() - Cleans a string to produce a string that can be safely used in an alias.
- ToUrlSegment() - Cleans a string to produce a string that can safely be used in an URL segment.
- ⭐ToCleanString() - Cleans a string by removing any unwanted characters and formatting it according to the provided options.
- SplitPascalCasing() - Splits a Pascal-cased string into a phrase separated by spaces.
- ToSafeFileName() - Cleans a string to produce a safe filename for use internally (on disk) or externally (as a URL).
- EscapedSplit() - Splits a string with an escape character that allows for the split character to exist within the string.
GetIdsFromPathReversed()
Parameters:
this string path
The GetIdsFromPathReversed()
extension method takes a string path and returns an array of integers that represent node ids in reverse order, from deepest to shallowest.
Example:
string path = "1,2,3";
int[] nodeIds = path.GetIdsFromPathReversed();
// nodeIds: [3, 2, 1]
StripWhitespace()
Parameters:
this string txt
The StripWhitespace()
extension method removes all new line and tab characters from a string. This method uses the Regex.Replace() method to replace any whitespace characters with an empty string.
Example:
string text = "Some text \n with \t whitespace";
string stripped = text.StripWhitespace();
// stripped: "Sometextwithwhitespace"
StripFileExtension()
Parameters:
this string fileName
The StripFileExtension()
extension method removes the file extension from a filename. This method checks if the filename contains any new line characters, and returns the original filename if it does. If the filename contains a file extension, it removes it using the Substring() method and returns the result.
Example:
string filename = "example.txt";
string stripped = filename.StripFileExtension();
// stripped: "example"
GetFileExtension()
Parameters:
this string file
The GetFileExtension()
extension method returns the file extension of a path or URL. This method uses a regular expression to match the last occurrence of a dot character before the start of a query string or the end of the string.
Example:
string path = "example.txt";
string extension = path.GetFileExtension();
// extension: ".txt"
DetectIsJson()
Parameters:
this string input
The DetectIsJson()
extension method checks if a string is a valid JSON string. This method trims the input string and checks if it starts with { and ends with } or starts with [ and ends with ].
Example:
string json = "{\"name\":\"John\"}";
bool isJson = json.DetectIsJson();
// isJson: true
DetectIsEmptyJson()
Parameters:
this string input
The DetectIsEmptyJson()
extension method checks if a string is an empty JSON array or object. This method replaces all whitespace characters with an empty string using a regular expression, and then checks if the resulting string is equal to [] or {}.
Example:
string json = " {} ";
bool isEmptyJson = json.DetectIsEmptyJson();
// isEmptyJson: true
ReplaceNonAlphanumericChars()
Parameters:
this string input, char replacement
The ReplaceNonAlphanumericChars()
extension method replaces any non-alphanumeric characters in a string with a specified replacement string or character.
Example:
var input = "This is a string with some non-alphanumeric characters: $100, @username";
var replacedString = input.ReplaceNonAlphanumericChars("-");
// replacedString: "This-is-a-string-with-some-non-alphanumeric-characters--100---username"
var replacedChar = input.ReplaceNonAlphanumericChars('_');
// replacedChar: "This_is_a_string_with_some_non_alphanumeric_characters__100___username"
CleanForXss()
Parameters:
this string input, params char[] ignoreFromClean
The CleanForXss()
extension method helps prevent cross-site scripting (XSS) attacks by stripping out potentially harmful characters from a string. It uses the StripHtml method to remove any HTML tags from the string, then removes any characters listed in a predefined list (CleanForXssChars). You can optionally specify additional characters to ignore by passing them as arguments to the method.
Example:
string userInput = "<script>alert('XSS!');</script>";
string sanitizedInput = userInput.CleanForXss();
// sanitizedInput: "alert('XSS!');"
ExceptChars()
Parameters:
this string str, HashSet<char> toExclude
The ExceptChars()
extension method removes all characters in a string that match a set of specified characters. It takes a HashSet as input, which contains the characters to exclude.
Example:
string input = "Hello, world!";
HashSet<char> excludedChars = new HashSet<char>(new[] { 'o', 'l' });
string output = input.ExceptChars(excludedChars);
// output: "He, wrd!"
GenerateStreamFromString()
Parameters:
this string s
The GenerateStreamFromString()
extension method converts a string into a stream object, which can be useful when working with streams in .NET.
Example:
string input = "Hello, world!";
Stream stream = input.GenerateStreamFromString();
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
var output = Encoding.UTF8.GetString(buffer);
// output: "Hello, world!"
AppendQueryStringToUrl()
Parameters:
this string url, params string[] queryStrings
The AppendQueryStringToUrl()
extension method appends a set of query string parameters to a URL. It ensures that the resulting URL is structured correctly, with only one '?' character and proper delimiters between parameters.
Example:
string url = "https://example.com";
string queryString = "foo=bar&baz=qux";
string result = url.AppendQueryStringToUrl(queryString);
// result: "https://example.com?foo=bar&baz=qux"
MakePluralName()
Parameters:
this string name
The MakePluralName()
extension method pluralizes a singular noun. It's a fun little extension method that uses a set of simple rules to convert a word into its plural form.
Example:
string singular = "apple";
string plural = singular.MakePluralName();
// plural: "apples"
IsVowel()
Parameters:
this char c
The IsVowel()
extension method checks whether a character is a vowel.
Example:
char c = 'a';
bool isVowel = c.IsVowel();
// isVowel: true
Trim()
Parameters:
this string value, string forRemoving
The Trim()
extension method trims a string using another string as the trim value. It works similarly to the built-in Trim method, but allows you to specify a string rather than a single character.
Example:
string input = "Hello, world!";
string trimValue = "Hdlr!";
string output = input.Trim(trimValue);
// output: ", wor"
EncodeJsString()
Parameters:
this string s
The EncodeJsString()
extension method encodes a string for use in JavaScript code. It replaces certain special characters with their escape codes.
Example:
string input = "Hello, \"world\"!";
string output = input.EncodeJsString();
// output: "Hello, \\\"world\\\"!"
EnsureStartsWith()
Parameters:
this string input, string toStartWith
,this string input, char value
The EnsureStartsWith()
extension method ensures that a string starts with a specified character or string. If the input string already starts with the specified character or string, the original string is returned. If not, the specified character or string is prepended to the input string.
Example:
string input = "world!";
string output = input.EnsureStartsWith("Hello, ");
// output: "Hello, world!"
EnsureEndsWith()
Parameters:
this string input, string toEndWith
,this string input, char value
The EnsureEndsWith()
extension method ensures that a string ends with a specified character or string. If the input string already ends with the specified character or string, the original string is returned. If not, the specified character or string is appended to the input string.
Example:
string input = "Hello,";
string output = input.EnsureEndsWith(" world!");
// output: "Hello, world!"
IsLowerCase()
Parameters:
this char ch
The IsLowerCase()
extension method checks whether a character is a lowercase letter or not.
Example:
char ch = 'a';
bool isLower = ch.IsLowerCase();
// isLower: True
char ch2 = 'A';
bool isNotLower = ch2.IsLowerCase();
// isNotLower: False
IsUpperCase()
Parameters:
this char ch
The IsUpperCase()
extension method checks whether a character is an uppercase letter or not.
Example:
char ch = 'A';
bool isUpper = ch.IsUpperCase();
// isUpper: True
char ch2 = 'a';
bool isNotUpper = ch2.IsUpperCase();
// isNotUpper: False
IsNullOrWhiteSpace()
Parameters:
this string? value
The IsNullOrWhiteSpace()
extension method checks whether a string is null, empty, or consists only of white-space characters.
Example:
string input = " ";
bool isNullOrWhiteSpace = input.IsNullOrWhiteSpace();
// isNullOrWhiteSpace: True
string input2 = " Hello ";
bool isNotNullOrWhiteSpace = input2.IsNullOrWhiteSpace();
// isNotNullOrWhiteSpace: False
IfNullOrWhiteSpace()
Parameters:
this string? str, string? defaultValue
The IfNullOrWhiteSpace()
extension method checks whether a string is null, empty, or consists only of white-space characters. If it is, it returns the default value provided; otherwise, it returns the input string.
Example:
string input = null;
string output = input.IfNullOrWhiteSpace("Hello, world!");
// output: "Hello, world!"
ToDelimitedList()
Parameters:
this string list, string delimiter = ","
The ToDelimitedList()
extension method converts a string containing a delimited list of items into an IList. By default, the delimiter is a comma (","), but a different delimiter can be specified.
Example:
string input = "one, two, three";
IList<string> output = input.ToDelimitedList();
// output: [ "one", "two", "three" ]
EnumTryParse()
Parameters:
this string strType, bool ignoreCase, out T? result
The EnumTryParse() extension method provides a safer way to parse a string value to a specified enum type. This method takes three parameters: the first parameter strType
is the string value that needs to be converted to the specified enum type, the second parameter ignoreCase
is a bool value that specifies whether the conversion should be case-insensitive, and the third parameter result
is an out parameter that holds the converted value.
Example:
string strValue = "Red";
bool success = strValue.EnumTryParse<Color>(true, out Color color); // Case-insensitive conversion
In the example above, we are converting a string value "Red" to a Color enum value. The second parameter true specifies that the conversion should be case-insensitive. If the conversion is not possible, this method will set the result parameter to null and return false. Otherwise, it will set the result parameter to the converted value and return true.
EnumParse()
Parameters:
this string strType, bool ignoreCase
The EnumParse<T>()
extension method provides an easy way to parse a string value to a specified enum type. This method takes two parameters: the first parameter strType is the string value that needs to be converted to the specified enum type, and the second parameter ignoreCase is a bool value that specifies whether the conversion should be case-insensitive.
Example:
string strValue = "Red";
Color color = strValue.EnumParse<Color>(true); // Case-insensitive conversion
In the example above, we are converting a string value "Red" to a Color enum value. The second parameter true specifies that the conversion should be case-insensitive. If the conversion is not possible, this method will throw an exception.
StripHtml()
Parameters:
this string text
The StripHtml()
extension method removes all HTML tags from a string. It is helpful when a user's input is in HTML format and needs to be displayed without HTML tags.
Example:
string input = "<p>Hello <b>world!</b></p>";
string output = input.StripHtml();
// output: "Hello world!"
EncodeAsGuid()
Parameters:
this string input
The EncodeAsGuid()
extension method encodes a string as a GUID. This method takes a string input, converts it into a hexadecimal format, and then returns a GUID based on the resulting hexadecimal string. This can be useful for scenarios like generating unique IDs.
Example:
string input = "Hello, world!";
Guid output = input.EncodeAsGuid();
// output: f2f8bf54-c72c-4db4-b35f-e21cb9cc4a4a
ConvertToHex()
Parameters:
this string input
The ConvertToHex()
extension method converts a string into its hexadecimal representation. Each character in the input string is converted to a two-digit hexadecimal value.
Example:
string input = "Hello, world!";
string output = input.ConvertToHex();
// output: 48656c6c6f2c20776f726c6421
DecodeFromHex()
Parameters:
this string hexValue
The DecodeFromHex()
extension method converts a hexadecimal string into its original string representation.
Example:
string input = "48656c6c6f2c20776f726c6421";
string output = input.DecodeFromHex();
// output: "Hello, world!"
ToUrlBase64()
Parameters:
this string input
The ToUrlBase64()
extension method encodes a string as a URL-safe Base64 string. This method replaces special characters in the output string with URL-safe equivalents.
Example:
string input = "Hello, world!";
string output = input.ToUrlBase64();
// output: "SGVsbG8sIHdvcmxkIQ=="
FromUrlBase64()
Parameters:
this string input
The FromUrlBase64()
extension method decodes a URL-safe Base64 string into its original string representation.
Example:
string input = "SGVsbG8sIHdvcmxkIQ==";
string output = input.FromUrlBase64();
// output: "Hello, world!"
InvariantFormat()
Parameters:
this string? format, params object?[] args
The InvariantFormat()
extension method formats a string with invariant culture. It is useful when formatting strings that need to be displayed across different cultures.
Example:
string output = "{0} is {1} years old.".InvariantFormat("John", 30);
// output: "John is 30 years old."
ToInvariantString()
Parameters:
this int str
,this long str
The ToInvariantString()
extension method converts an integer or long value to its invariant string representation.
Example:
int input = 42;
string output = input.ToInvariantString();
// output: "42"
InvariantEquals()
Parameters:
this string? compare, string? compareTo
The InvariantEquals()
extension method compares two strings in a case-insensitive manner and with invariant culture.
Example:
string input1 = "Hello, world!";
string input2 = "hello, World!";
bool output = input1.InvariantEquals(input2);
// output: true
InvariantStartsWith()
Parameters:
this string compare, string compareTo
The InvariantStartsWith()
extension method is used to check if a string starts with a specific substring. This method performs a case-insensitive comparison using the InvariantCultureIgnoreCase option.
Example:
string input = "Hello World";
bool result = input.InvariantStartsWith("Hello");
// result: true
InvariantEndsWith()
Parameters:
this string compare, string compareTo
The InvariantEndsWith()
extension method is used to check if a string ends with a specific substring. This method performs a case-insensitive comparison using the InvariantCultureIgnoreCase option.
Example:
string input = "Hello World";
bool result = input.InvariantEndsWith("world");
// result: true
InvariantContains()
Parameters:
this string compare, string compareTo
,this IEnumerable<string> compare, string compareTo
The InvariantContains()
extension methods are used to check if a string or IEnumerable of strings contains a specific substring. This method performs a case-insensitive comparison.
Example:
string input = "Hello World";
bool result1 = input.InvariantContains("world");
// result1: true
string[] words = { "hello", "world", "dotnet" };
bool result2 = words.InvariantContains("DoTnEt");
// result2: true
InvariantIndexOf()
Parameters:
this string s, string value
The InvariantIndexOf()
extension method is used to find the index of the first occurrence of a specific substring in a string. This method performs a case-insensitive comparison using the OrdinalIgnoreCase option.
Example:
string input = "Hello World";
int index = input.InvariantIndexOf("world");
// index: 6
InvariantLastIndexOf()
Parameters:
this string s, string value
The InvariantLastIndexOf()
extension method is used to find the index of the last occurrence of a specific substring in a string. This method performs a case-insensitive comparison using the OrdinalIgnoreCase option.
Example:
string input = "Hello World, hello world!";
int index = input.InvariantLastIndexOf("world");
// index: 18
ParseInto()
Parameters:
this string val, Type type
The ParseInto()
extension method attempts to parse a string into the supplied type by finding and using the Type's "Parse" method. It can be used to convert a string representation of a value to an instance of that value's type. There are two overloads of this method: one that returns the parsed value directly and another that returns an object that can be cast to the target type.
Example:
string str = "123";
int i = (int)str.ParseInto(typeof(int));
// i: 123
The method also accepts a type parameter which I favour over the two.
ParseInto<T>(this string val)
Example:
string str = "123";
int i = str.ParseInto<int>();
// i: 123
GenerateHash()
Parameters:
this string str
The GenerateHash()
extension method is used to generate a hash of a string using a specified hash algorithm. There are two overloads of this method: one that uses the FIPS compliance setting and another that takes a generic type parameter specifying the hash algorithm to use. The default hash algorithm used by the ToSHA1 method is SHA1.
Example:
string str = "Hello World!";
string md5Hash = str.GenerateHash<MD5>();
// md5Hash: "5eb63bbbe01eeed093cb22bb8f5acdc3"
ToSHA1()
Parameters:
this string stringToConvert
The ToSHA1()
extension method is a shorthand for GenerateHash("SHA1"). It is used to convert a string to its SHA1 hash value.
Example:
string str = "Hello World!";
string sha1Hash = str.ToSHA1();
// sha1Hash: "0a4d55a8d778e5022fab701977c5d840bbc486d0"
UrlTokenDecode()
Parameters:
this string input
The UrlTokenDecode()
extension method decodes a string that was encoded with UrlTokenEncode. It is used to convert a string that has been encoded using the UrlTokenEncode method back to its original byte array representation.
Example:
string str = "SGVsbG8sIHdvcmxkIQ==";
byte[] decodedBytes = str.UrlTokenDecode();
// decodedBytes: [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
UrlTokenEncode()
Parameters:
this byte[] input
The UrlTokenEncode()
extension method encodes a byte array for use in URLs, files, or other places where a string is required. It converts the input byte array to a Base64 string and replaces characters that could cause problems in URLs.
Example:
string input = "Hello, world!";
byte[] bytes = Encoding.UTF8.GetBytes(input);
string output = bytes.UrlTokenEncode();
// output: "SGVsbG8sIHdvcmxkIQ=="
NormaliseDirectoryPath()
Parameters:
this string currentFolder
The NormaliseDirectoryPath()
extension method ensures that a given directory path ends with a directory separator character. It is useful when dealing with directory paths in different platforms, as Windows uses \ and Unix uses /.
Example:
string input = @"C:\Program Files\MyApp";
string output = input.NormaliseDirectoryPath();
// output: "C:\\Program Files\\MyApp\\"
Truncate()
Parameters:
this string text, int maxLength, string suffix = "..."
The Truncate()
extension method truncates a given string to a specified length and appends a suffix at the end of it. It is useful when displaying a long text on a user interface and we want to limit its length.
Example:
string input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent convallis dolor vel augue imperdiet mollis.";
string output = input.Truncate(50);
// output: "Lorem ipsum dolor sit amet, consectetur adipisci..."
StripNewLines()
Parameters:
this string input
The StripNewLines()
extension method removes carriage returns and line feeds from a given string. It is useful when we want to clean up a string and remove any line breaks.
Example:
string input = "Hello\nWorld\r\n!";
string output = input.StripNewLines();
// output: "HelloWorld!"
ToSingleLine()
Parameters:
this string text
The ToSingleLine()
extension method converts a multiline string to a single line by replacing line breaks with spaces. It is useful when we want to concatenate a multiline string into a single line.
Example:
string input = "Lorem ipsum dolor sit amet,\r\nconsectetur adipiscing elit.\nSed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
string output = input.ToSingleLine();
// output: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
OrIfNullOrWhiteSpace()
Parameters:
this string input, string alternative
The OrIfNullOrWhiteSpace()
extension method returns the input string if it is not null or whitespace, otherwise, it returns the alternative string. It is useful when we want to provide a default value for a string if it is empty.
Example:
string input = "";
string output = input.OrIfNullOrWhiteSpace("Hello, world!");
// output: "Hello, world!"
ToFirstUpper()
Parameters:
this string input
,this string input, CultureInfo culture
The ToFirstUpper()
extension method converts the first character of a string to uppercase. It takes an optional CultureInfo parameter to specify the culture-specific casing rules to be used. If the input string is null or contains only whitespace, the method returns the input string without modification.
Example:
string input = "hello, world!";
string output = input.ToFirstUpper();
// output: "Hello, world!"
string input2 = "hello, world!";
string output2 = input2.ToFirstUpper(CultureInfo.GetCultureInfo("tr-TR"));
// output2: "Hello, World!"
ToFirstLower()
Parameters:
this string input
,this string input, CultureInfo culture
The ToFirstLower()
extension method converts the first character of a string to lowercase. It takes an optional CultureInfo parameter to specify the culture-specific casing rules to be used. If the input string is null or contains only whitespace, the method returns the input string without modification.
Example:
string input = "HELLO, WORLD!";
string output = input.ToFirstLower();
// output: "hELLO, WORLD!"
string input2 = "HELLO, WORLD!";
string output2 = input2.ToFirstLower(CultureInfo.GetCultureInfo("tr-TR"));
// output2: "hello, World!"
ToFirstUpperInvariant() / ToFirstLowerInvariant()
Parameters:
this string input
The ToFirstUpperInvariant()
and ToFirstLowerInvariant()
extension methods are similar to ToFirstUpper()
and ToFirstLower()
, respectively, but they use the casing rules of the invariant culture.
Example:
string input = "hello, world!";
string output = input.ToFirstUpperInvariant();
// output: "Hello, world!"
string input2 = "HELLO, WORLD!";
string output2 = input2.ToFirstLowerInvariant();
// output2: "hELLO, WORLD!"
ReplaceMany()
Parameters:
this string text, IDictionary<string, string> replacements
,this string text, char[] chars, char replacement
The ReplaceMany()
extension method replaces multiple occurrences of a set of characters or strings in a given string with a specified replacement character or string.
The first overload of the method takes an IDictionary parameter, where each key-value pair represents the string to be replaced and the string to replace it with.
Example:
string input = "The quick brown fox jumps over the lazy dog.";
var replacements = new Dictionary<string, string> { { "quick", "slow" }, { "brown", "red" } };
string output = input.ReplaceMany(replacements);
// output: "The slow red fox jumps over the lazy dog."
string input2 = "The quick brown fox jumps over the lazy dog.";
char[] chars2 = { 'q', 'b', 'f' };
char replacement2 = '-';
string output2 = input2.ReplaceMany(chars2, replacement2);
// output2: "The ---k ---rown ox jumps over the lazy dog."
ReplaceFirst()
Parameters:
this string text, string search, string replace
The ReplaceFirst()
extension method returns a new string in which only the first occurrence of a specified string is replaced by a specified replacement string.
Example:
string input = "Hello, world!";
string output = input.ReplaceFirst("o", "0");
// output: Hell0, world!
Replace()
Parameters:
this string source, string oldString, string newString, StringComparison stringComparison
The Replace()
extension method returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string. StringComparison specifies the type of search to use for the specified string.
Example:
string input = "HELLO, world!";
string output = input.Replace("o", "0", StringComparison.OrdinalIgnoreCase);
// output: HELL0, w0rld!
ToCSharpString()
Parameters:
this string s
The ToCSharpString()
extension method converts a literal string into a C# expression.
Example:
string input = "Hello, world!";
string output = input.ToCSharpString();
// output: "Hello, world!"
EscapeRegexSpecialCharacters()
Parameters:
this string text
The EscapeRegexSpecialCharacters()
extension method escapes all the special characters used in a regular expression.
Example:
string input = "hello[world].";
string output = input.EscapeRegexSpecialCharacters();
// output: hello\[world\]\.
ContainsAny()
Parameters:
this string haystack, IEnumerable<string> needles, StringComparison comparison = StringComparison.CurrentCulture
The ContainsAny()
extension method checks whether a string "haystack" contains within it any of the strings in the "needles" collection and returns true if it does or false if it doesn't.
Example:
string input = "Hello, world!";
bool output = input.ContainsAny("o", "0", "1");
// output: true
CsvContains()
Parameters:
this string csv, string value
The CsvContains()
extension method checks if a comma-separated string (CSV) contains a given value. It splits the input string into a list and uses the Contains() method to check if the value is in the list.
Example:
string csv = "apple,banana,cherry,date,elderberry";
string value = "cherry";
bool output = csv.CsvContains(value1);
// output: true
string value2 = "kiwi";
bool output2 = csv.CsvContains(value2);
// output2: false
ToFriendlyName()
Parameters:
this string fileName
The ToFriendlyName()
extension method can convert a file name to a user-friendly name for a content item. It performs several string manipulations to transform the file name, including stripping the file extension, replacing underscores and dashes with spaces, converting to title case, and replacing consecutive spaces with a single space.
Example:
string fileName = "the_quick_brown-fox.txt";
string friendlyName = fileName.ToFriendlyName();
// friendlyName: "The Quick Brown Fox"
ToValidXmlString()
Parameters:
this string text
The ToValidXmlString()
extension method returns a new string in which all occurrences of Unicode characters that are invalid in XML files are replaced with an empty string. It uses a regular expression to filter out control characters but allows only properly-formed surrogate sequences.
Example:
string text = "This is a \u0001 test string \uDC00 with invalid characters.";
string validXmlString = text.ToValidXmlString();
//validXmlString: "This is a test string with invalid characters."
ToGuid()
Parameters:
this string text
The ToGuid()
extension method converts a string to a GUID (Globally Unique Identifier). It creates a name-based UUID using the algorithm from RFC 4122 §4.3, which generates a deterministic GUID that is dependent on the namespace and name. Depending on the input string, the resulting GUID may not be unique.
Example:
string text = "This is a test string";
Guid guid = text.ToGuid();
//guid: {B6C89F6F-DA6F-3246-9F77-2CE7C8885CF5}
NullOrWhiteSpaceAsNull()
Parameters:
this string? text
The NullOrWhiteSpaceAsNull()
extension method turns a null-or-whitespace string into a null string.
Example:
string text = " ";
string result = text.NullOrWhiteSpaceAsNull();
// result: null
IsFullPath()
Parameters:
this string path
The IsFullPath()
extension method provides a quick way to check whether a given path is a full path including drive letter. This method takes one parameter path, which is a string value representing the path to be checked.
Example:
string path = @"C:\Program Files\Microsoft";
bool isFullPath = path.IsFullPath();
// isFullPath: True
In the example above, we are checking whether the given path @"C:\Program Files\Microsoft"
is a full path including drive letter. The return value is true because the path includes a drive letter.
ToSafeAlias()
Parameters:
this string alias, IShortStringHelper? shortStringHelper
,(this string alias, IShortStringHelper shortStringHelper, bool camel
,this string alias, IShortStringHelper shortStringHelper, string culture
The ToSafeAlias()
extension method is designed to clean a string to produce a string that can be safely used in an alias. It takes a string parameter and an object of IShortStringHelper. IShortStringHelper is an interface that specifies a few methods to clean a string and return a safe one. If you don't provide a IShortStringHelper object, you will get a NullReferenceException. For this example I am using DI to inject Umbraco.Cms.Core.Strings.IShortStringHelper
as the _shortStringHelper
variable.
Example:
string alias = "Sample alias: $@$*2-+()";
string safeAlias = alias.ToSafeAlias(_shortStringHelper);
// safeAlias: "samplealias22"
You can also pass a bool value for camel, which means you want the alias to be camel-cased. If camel is true, then the first character of the alias will be converted to lower case.
Example:
string alias = "Sample alias: $@$*2-+()";
string safeAlias = alias.ToSafeAlias(_shortStringHelper, true);
// safeAlias: "sampleAlias22"
Lastly, you can clean a string in the context of a specified culture by passing a string value for culture. The alias will then be cleaned up to be used safely as an alias in the context of that specific culture.
Example:
string alias = "Sample alias: $@$*2-+()";
string safeAlias = alias.ToSafeAlias(_shortStringHelper, "en-US");
// safeAlias: "samplealias22"
ToUrlSegment()
Parameters:
this string text, IShortStringHelper shortStringHelper
,this string text, IShortStringHelper shortStringHelper, string? culture
The ToUrlSegment()
extension method is designed to clean a string to produce a string that can safely be used in an URL segment. It takes a string parameter and an object of IShortStringHelper. IShortStringHelper is an interface that specifies a few methods to clean a string and return a safe one. If you don't provide a IShortStringHelper object, you will get a NullReferenceException.
Example:
string text = "Text to clean: $@$*2-+()";
string urlSegment = text.ToUrlSegment(new DefaultShortStringHelper());
// urlSegment: "text-to-clean-22"
You can also clean a string, using a specified culture, to produce a string that can safely be used in an URL segment by passing a string value for culture.
Example:
string text = "Text to clean: $@$*2-+()";
string urlSegment = text.ToUrlSegment(new DefaultShortStringHelper(), "en-US");
// urlSegment: "text-to-clean-22"
ToCleanString()
Parameters:
this string text, IShortStringHelper shortStringHelper, CleanStringType stringType
,this string text, IShortStringHelper shortStringHelper, CleanStringType stringType, char separator
,this string text, IShortStringHelper shortStringHelper, CleanStringType stringType, string culture
,this string text, IShortStringHelper shortStringHelper, CleanStringType stringType, char separator, string culture
The ToCleanString()
extension method cleans a string by removing any unwanted characters and formatting it according to the provided options. This can be useful when working with strings that need to conform to certain conventions, such as URLs or file names.
Example:
string input = "The Quick Brown Fox Jumps Over The Lazy Dog.";
string output = input.ToCleanString(new DefaultShortStringHelper(), CleanStringType.UrlFriendly);
// output: "the-quick-brown-fox-jumps-over-the-lazy-dog"
In the above example, the input string is cleaned up to be URL friendly using the default short string helper. Other options for stringType include PascalCase and CamelCase. If a separator is specified, it will be used to separate words in the output string.
The ToCleanString()
method can also take an optional culture parameter to specify a specific culture to use when cleaning the string.
string input = "The Quick Brown Fox Jumps Over The Lazy Dog.";
string output = input.ToCleanString(new DefaultShortStringHelper(), CleanStringType.CamelCase, '_', "en-US");
// output: "the_Quick_Brown_Fox_Jumps_Over_The_Lazy_Dog"
In this example, the input string is cleaned up to be camelCase and the separator is set to an underscore. The culture parameter is set to "en-US".
SplitPascalCasing()
Parameters:
this string phrase, IShortStringHelper shortStringHelper
The SplitPascalCasing()
extension method splits a Pascal-cased string into a phrase separated by spaces. It is useful for displaying text in a more readable format.
Example:
string input = "PascalCasedString";
string output = input.SplitPascalCasing(new ShortStringHelper());
// output: "Pascal Cased String"
ToSafeFileName()
Parameters:
this string text, IShortStringHelper shortStringHelper
,this string text, IShortStringHelper shortStringHelper, string culture
The ToSafeFileName()
extension method cleans a string to produce a safe filename for use internally (on disk) or externally (as a URL). It replaces characters that are not safe for filenames with safe equivalents.
Example:
string input = "Some filename with spaces.txt";
string output = input.ToSafeFileName(new ShortStringHelper());
// output: "Some_filename_with_spaces.txt"
The ToSafeFileName() extension method also has an overload that takes a culture parameter, allowing you to specify the culture context for cleaning the string.
Example:
string input = "Some filename with spaces.txt";
string output = input.ToSafeFileName(new ShortStringHelper(), "en-US");
// output: "Some_filename_with_spaces.txt"
EscapedSplit()
Parameters:
this string value, char splitChar, char escapeChar = DefaultEscapedStringEscapeChar
The EscapedSplit()
extension method splits a string with an escape character that allows for the split character to exist within the string. This is useful when dealing with strings that contain characters that are used to split the string into parts.
Example:
string input = "one|two\\|three|four";
IEnumerable<string> output = input.EscapedSplit('|', '\\');
// output: ["one", "two|three", "four"]
Source: GitHub
Thank You For Reading!
What are your favourites? Let me know in the comments section below 👇
Top comments (0)