JSFiddle - React, Tailwind, and code Playground

by NickU

JavaScript

/* =========================
   $trim (switch version)
   ========================= */
function $trim(s) {
    try {
        if (s == null) return "";

        switch (typeof s) {
            case "string":
                return s.trim();

            case "number":
            case "boolean":
            case "bigint":
                return String(s);

            case "function":
                console.error("$trim(): received a function instead of a value.", s);
                return "";

            case "object":
                if (typeof jQuery !== "undefined" && s instanceof jQuery) {
                    console.error("$trim(): received a jQuery object — use s.val().", s);
                    return "";
                }
                if (typeof Element !== "undefined" && s instanceof Element) {
                    console.error("$trim(): received a DOM element — use element.value.", s);
                    return "";
                }

                if (typeof s.trim === "function") return s.trim();

                if (typeof s.valueOf === "function") {
                    const v = s.valueOf();
                    if (typeof v === "string") return v.trim();
                }

                if (typeof s.toString === "function") {
                    const t = s.toString();
                    if (typeof t === "string") return t.trim();
                }

                console.warn("$trim(): unsupported object type:", s);
                return "";

            case "symbol":
            case "undefined":
            default:
                console.warn("$trim(): invalid type:", typeof s, s);
                return "";
        }
    } catch (err) {
        console.error("$trim(): exception:", err, s);
        return "";
    }
}

/* =========================
   Test Harness
   ========================= */
(function run$trimTests() {
    const results = [];
    const original = {
 ...