lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Thu, Aug 14, 2008 at 5:41 PM, Petite Abeille
<petite.abeille@gmail.com> wrote:
> Hello,
>
> Does anyone have implemented John Gruber's "Title Case" algorithm in Lua?
>
> http://daringfireball.net/2008/05/title_case
> http://daringfireball.net/2008/08/title_case_update
>
> Cheers,
>
> PA.
>

Here's a first draft based (heavily) on the Javascript implementation
by David Gouch rather than the original Perl version:


local smallwords = {
  a=1, ["and"]=1, as=1, at=1, but=1, by=1, en=1, ["for"]=1, ["if"]=1,
  ["in"]=1, of=1, the=1, to=1, vs=1, ["vs."]=1, v=1, ["v."]=1, via=1
}

function string.titlecase(title)
  return string.gsub(title, "()([%w&`'''\"".@:/{%(%[<>_]+)(-? *)()",
    function(index, nonspace, space, endpos)
      local low = nonspace:lower();
      if (index > 1) and (title:sub(index-2,index-2) ~= ':')
            and (endpos < #title) and smallwords[low] then
        return low .. space;
      elseif title:sub(index-1, index+1):match("['\"_{%(%[]/)") then
        return nonspace:sub(1,1) .. nonspace:sub(2,2):upper()
           .. nonspace:sub(3) .. space;
      elseif nonspace:sub(2):match("[A-Z&]")
            or nonspace:sub(2):match("%w[%._]%w") then
        return nonspace .. space;
      end
      return nonspace:sub(1,1):upper() .. nonspace:sub(2) .. space;
    end);
end


...there may still be some issues with it, but it's pretty close.