Table of Contents

Class StringExtensions

Namespace
Htmx.Components.Extensions
Assembly
Htmx.Components.dll

Provides extension methods for string manipulation and formatting in the HTMX Components library.

public static class StringExtensions
Inheritance
StringExtensions
Inherited Members

Remarks

These extensions provide utilities for HTML attribute formatting, template processing, and type-specific string conversion that are commonly needed in web component scenarios.

Methods

ConvertToInputString<T>(T)

Converts a value to its string representation suitable for HTML input elements.

public static string ConvertToInputString<T>(this T value)

Parameters

value T

The value to convert to a string.

Returns

string

A string representation of the value formatted for HTML inputs.

Type Parameters

T

The type of the value to convert.

Examples

DateTime date = new DateTime(2023, 12, 25);
string dateStr = date.ConvertToInputString(); // Returns "2023-12-25T00:00:00"

bool flag = true;
string flagStr = flag.ConvertToInputString(); // Returns "true"

Remarks

This method provides type-specific formatting for common .NET types to ensure they are represented correctly in HTML input elements. It handles:

  • DateTime values in ISO format
  • DateTimeOffset values in date format
  • TimeSpan values in time format
  • Boolean values as "true"/"false"
  • Enum values as string representations
  • Numeric values using invariant culture

SanitizeForHtmlId(string)

Sanitizes a string to be safe for use as an HTML element ID or CSS class name.

public static string SanitizeForHtmlId(this string input)

Parameters

input string

The string to sanitize.

Returns

string

A sanitized string safe for use in HTML attributes.

Examples

string unsafeId = "user name!@#";
string safeId = unsafeId.SanitizeForHtmlId(); // Returns "user_name___"

Remarks

This method replaces any character that is not a letter, digit, hyphen, underscore, or colon with an underscore. This ensures the resulting string can be safely used as an HTML ID or CSS class name according to HTML specifications.

Exceptions

ArgumentNullException

Thrown when input is null.