Skip to content

Commit

Permalink
feat: adding more string extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
ja0b committed May 7, 2021
1 parent 9ca281e commit 648090c
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public static class Separators
public const string Vertical = "|";
public const string Hyphen = "-";
public const string HtmlNewLine = "<br />";
public const string QuestionMark = "?";
}
}
}
50 changes: 49 additions & 1 deletion Source/Cogworks.Essentials/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ public static bool HasValue(this string input)
=> !string.IsNullOrWhiteSpace(input);

public static Uri ToUri(this string urlString)
=> new Uri(urlString);
=> urlString.HasValue()
? new Uri(urlString)
: null;

public static string ToCamelCase(this string original)
{
Expand Down Expand Up @@ -222,5 +224,51 @@ public static string RemoveNewLines(this string input)
.Replace("\r", string.Empty)
.Replace(Environment.NewLine, string.Empty)
: string.Empty;

public static string GetIpAddressWithoutPort(this string ipAddress)
{
var portIndex = ipAddress.IndexOf(':');

return portIndex < 0
? ipAddress
: ipAddress.Substring(0, portIndex);
}

public static string AddOrUpdateQueryParameter(this string url, string queryKey, string queryValue)
{
var splitted = url.Split(Separators.QuestionMark.ToCharArray());
var queryString = HttpUtility.ParseQueryString(splitted.Skip(1).FirstOrDefault() ?? string.Empty);

queryString[queryKey] = queryValue;

return $"{splitted.FirstOrDefault()}?{queryString}";
}

/// <summary>
/// Strips out <P> and </P> tags if they were used as a wrapper
/// for other HTML content.
/// </summary>
/// <param name="text">The HTML text.</param>
public static string RemoveParagraphWrapperTags(this string text)
{
if (!text.HasValue())
{
return text;
}

var trimmedText = text.Trim();
var paragraphIndex = trimmedText.IndexOf("<p>", StringComparison.Ordinal);

if (paragraphIndex != 0
|| paragraphIndex != trimmedText.LastIndexOf("<p>", StringComparison.Ordinal)
|| trimmedText.Substring(trimmedText.Length - 4, 4) != "</p>")
{
// Paragraph not used as a wrapper element
return text;
}

// Remove paragraph wrapper tags
return trimmedText.Substring(3, trimmedText.Length - 7);
}
}
}

0 comments on commit 648090c

Please sign in to comment.