Jump to content

Module:String

From Apogea Wiki

Documentation for this module may be created at Module:String/doc

local p = {}

-- Title case a string (capitalize first letter of each word)
-- Handles common exceptions like "of", "the", "and" etc.
function p.titleCase(frame)
    local s = frame.args[1] or ""
    if s == "" then return "" end
    
    -- Words that should stay lowercase (unless first word)
    local exceptions = {
        ["a"] = true,
        ["an"] = true,
        ["and"] = true,
        ["as"] = true,
        ["at"] = true,
        ["but"] = true,
        ["by"] = true,
        ["for"] = true,
        ["in"] = true,
        ["of"] = true,
        ["on"] = true,
        ["or"] = true,
        ["the"] = true,
        ["to"] = true,
        ["with"] = true,
    }
    
    local result = {}
    local isFirst = true
    
    for word in s:gmatch("%S+") do
        local lower = word:lower()
        if isFirst or not exceptions[lower] then
            -- Capitalize first letter, lowercase rest
            word = lower:gsub("^%l", string.upper)
        else
            word = lower
        end
        table.insert(result, word)
        isFirst = false
    end
    
    return table.concat(result, " ")
end

return p