In Lua, how can I remove a word from a string which can be preceded for certain character or not?

170 Views Asked by At

Lets say I have a string like this:

And I need to add and delete names at will. What would be the better way of doing it without the risk of leaving any leading ";" here and there? Since, depending on its position, the name could be preceded for a ";" or not... Well, my first tries are being something in this line:

<script src="//github.com/fengari-lua/fengari-web/releases/download/v0.1.4/fengari-web.js"></script>
<script type="application/lua">

    local names = " Pic One; Pic Three; Pic Eight; Pic Two" -- The first emoji results missing after processing
    local picName = " Pic One"

    if not names:match(picName) then
        names = names .. ";" .. picName --addition
    else
        names = names:gsub(";?" .. picName, "") --deletion
    end
    names  = names:sub(1, 1) == ";" and names:sub(2) or names -- Instead of my first try: names = names:sub(2)
    print(names)

</script>

But I'm sure there is an approach out there much more reliable and elegant (pattern based, for example) I'm not finding, so here I'm...

EDIT¹: New code accordingly to @shingo suggestion (thanks!), which seems to work fine, EXCEPT when the first name starts with emoji, cause it results removed for some reason...

EDIT²: A try to fix the first missing emoji issue that seems to wor- erm... not, it seems it gets added again instead of being removed as can be seen... I think now the problem is I'm removing the fist ";" and, as the code is right now, it expects to find everything starting with a ";"? But I'd like not to store that first leading ";" if possible for the exposed reasons.

0

There are 0 best solutions below