Better way of doing multiple replaces?

Hi.

I have an existing snippet that I wrote, which transforms a list of comma delimuted labels from the clipboard.

Original Text
SS,Shrinking,Fire Country,A Million Little Things,The Good Doctor,Quantum Leap,Chicago Fire,Grey's Anatomy,Magnum P.I.,911,NCIS,NCIS: Hawaii,POTM,

And it then performs several replacements to make that list into a list of hashtags for things like twitter/facebook/instagram etc, so that the out put looks like this.

Output
#ss #shrinking #firecountry #amillionlittlethings #thegooddoctor #quantumleap #chicagofire #greysanatomy #magnumpi #911 #ncis #ncishawaii #potm

It works perfectly, but I always like elegant code and I'm not sure my code below is the most optimal.

Is there a better way to write this code? In particular, the multiple replaces. Seems like that could be improved with maybe a regex or something.

{cliptext=lower({clipboard})}
{mytext=substring(cliptext, 1, len(cliptext)-1)}
{cleantext=replace(replace(replace(replace(replace(replace(replace(replace(replace(mytext, "-", ""), ".", ""), "&", ""), ")", ""), "(", ""), ":", ""), " ", ""), ",", " #"), "'", "")}
#{=cleantext}

Hey Andy! We can probably rephrase your question as "how to clear multiple characters at once".

First way is to use replaceregex(cliptext, "[-.&()]", "", "g"). The square brackets indicate a character class, which matches any one of the contained characters.

Another fancy (but ineffecient) way is to split the string at all those characters and then join it all back, effectively clearing them out: join(splitregex(cliptext, "[-.&()]", "g"), "").

Docs link

Let me know if it works for you.

1 Like

Ha brilliant.

Final snippet now looks like this.

Much better thanks !!

{origtext=substring(lower({clipboard}), 1, len({clipboard})-1)}{cleantext=replaceregex(origtext, "[ ()&.:@'-]", "", "g")}{hashtext=replaceregex(cleantext, "[,]", " #", "g")}{=concat("#",hashtext)}

2 Likes