@nish1896/rhf-mui-components
Version:
A suite of 25+ production-ready react-hook-form components built with material-ui. Fully typed, tree-shakable, and optimized for enterprise-grade forms.
53 lines (52 loc) • 2.07 kB
JavaScript
//#region src/utils/text-transform.ts
/**
* Function to generate easy-to-read form labels from a given string.
*
* Examples -
* "fullName" to "Full Name"
* "last_name" to "Last Name"
* "parseJSONData" to "Parse JSON Data"
* "enable_HTTP_Config" to "Enable HTTP Config"
* users.0.email -> Users Email
*/
function fieldNameToLabel(str) {
return str.replace(/\.\d+/g, "").replace(/[._]/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/\b\w/g, (char) => char.toUpperCase()).trim();
}
function fieldNameToId(fieldName) {
return fieldName.replace(/\[(\d+)\]/g, "-$1").replace(/\./g, "-").replace(/[^a-zA-Z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
}
function normalizeString(str) {
return str.trim().toLowerCase().replace(/\s+/g, "");
}
/**
* Strips/truncates pasted text to fit the active numeric constraints.
* Returns `null` when nothing salvageable remains.
*
* @example
* sanitizePastedNumber('43.234', false, true) // '43' (onlyIntegers)
* sanitizePastedNumber('-43.5', true, false) // '43.5' (nonNegative strips '-')
* sanitizePastedNumber('3.14159', false, false, 2) // '3.14' (maxDecimalPlaces=2)
* sanitizePastedNumber('-3.999', false, true) // '-3' (both sign + integer)
*/
function sanitizePastedNumber(raw, nonNegative, onlyIntegers, maxDecimalPlaces) {
let s = raw.trim();
if (!s) return null;
let sign = "";
if (s.startsWith("-")) {
if (!nonNegative) sign = "-";
s = s.slice(1);
}
s = s.replace(/[^0-9.]/g, "");
const firstDot = s.indexOf(".");
if (firstDot !== -1) s = s.slice(0, firstDot + 1) + s.slice(firstDot + 1).replace(/\./g, "");
if (onlyIntegers) s = s.split(".")[0];
else if (maxDecimalPlaces !== void 0) {
const n = Math.max(0, Math.floor(maxDecimalPlaces));
const [intPart, decPart] = s.split(".");
s = decPart !== void 0 ? intPart + (n > 0 ? `.${decPart.slice(0, n)}` : "") : intPart;
}
s = (sign + s).replace(/\.$/, "");
return s || null;
}
//#endregion
export { fieldNameToId, fieldNameToLabel, normalizeString, sanitizePastedNumber };