Module:WordCount

From Elanthipedia
Jump to navigation Jump to search

To insert a word count on a page use the following code:

{{#invoke:WordCount|count|{{{content|}}} }} words


local p = {}

function p.count(frame)
    -- Get the content from the template
    local text = frame.args[1] or ""
    
    -- 1. Remove HTML tags (like <br />)
    text = text:gsub("<[^>]*>", "")
    
    -- 2. Remove wiki-links syntax but keep the words inside
    -- Transforms [[Link|Text]] into Text
    text = text:gsub("%[%[[^%|%]]*%|([^%]]*)%]%]", "%1")
    -- Transforms [[Link]] into Link
    text = text:gsub("%[%[([^%]]*)%]%]", "%1")
    
    -- 3. Count non-whitespace sequences
    local _, count = text:gsub("%S+", "")
    
    return count
end

return p